3.Longest Substring Without Repeating Characters
2015-08-15 14:24
351 查看
Longest Substring Without Repeating
Characters
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating
letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
solution: The traditional way to slove it is O(n^3). Our solution is O(n). Set an array a[300] to represent all character and set it
to 0 for start. set i = 0. For each entry j in array, if the a[s.charAt(j)-' ']==0, it means s.charAt(j) has not appeared, and make a[s.charAt(j)-'
']=1 , store the current len j-i+1. and move on. if the a[s.charAt(j)-' ']==1 which tell us it repeatd. to reset the a from the position
i, set the a[s.charAt(i)-' ']=1 until we remove the
s.charAt(j). Then make the a[s.charAt(j)-' ']=1 to contiune find.
Note
that we use array to for the current substring (between i and j), another way is use hashset.
Characters
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating
letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
solution: The traditional way to slove it is O(n^3). Our solution is O(n). Set an array a[300] to represent all character and set it
to 0 for start. set i = 0. For each entry j in array, if the a[s.charAt(j)-' ']==0, it means s.charAt(j) has not appeared, and make a[s.charAt(j)-'
']=1 , store the current len j-i+1. and move on. if the a[s.charAt(j)-' ']==1 which tell us it repeatd. to reset the a from the position
i, set the a[s.charAt(i)-' ']=1 until we remove the
s.charAt(j). Then make the a[s.charAt(j)-' ']=1 to contiune find.
Note
that we use array to for the current substring (between i and j), another way is use hashset.
public class Solution { public int lengthOfLongestSubstring(String s) { int []a = new int[300]; for (int k=0;k<300;k++) { a[k] = 0; } int i,j; int len = 0; for (i=0,j=0;j<s.length();j++) { if (a[s.charAt(j)-' '] == 0) { a[s.charAt(j)-' '] = 1; if(j-i+1 >len) { len = j-i+1; } } else { while (a[s.charAt(j)-' '] == 1) { a[s.charAt(i)-' '] = 0; i++; } a[s.charAt(j)-' '] = 1; } } return len; } }
相关文章推荐
- 解释用uml画图各个类之间关系
- HashMap与ConcurrentHashMap的区别
- 贪心算法实例讲解(1)
- 牛顿的八字养生经
- 百度搜索引擎排名原理、因素
- 【Lua】__newindex
- 拓扑排序算法
- 在将String写入txt文件时的换行问题
- ios开发问题汇总
- python学习第一天
- 牛顿
- 无题II
- Jquery幻灯片特效代码分享--鼠标点击按钮时切换(1)
- 自学TDTK(TowerDefenceToolKIt)(1)
- 黑马程序员一一String类和StringBuffer,StringBuilder笔记
- 二叉树 (Binary Tree)相关题目(求总节点数 叶子节点数 深度 第k层节点数)
- HDU1175 连连看
- HDU 5137--How Many Maos Does the Guanxi Worth【枚举 && 最短路 && spfa】
- iOS sqlite3 使用
- 杂题 - hdu5357 Easy Sequence