Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
我自己的代码:
public class Solution {
public int lengthOfLongestSubstring(String s) {
int slenmax=0;
for(int i=0;i<s.length();i++)
{
int j=i+1;
boolean flag=true;
while(j<s.length()&&flag)
{
for(int k=i;k<j;k++)
{ if(s.charAt(j)==s.charAt(k))
{
flag=false;
j--;
}
}
j++;
}
int slen=j-i;
if(slen>slenmax)
slenmax=slen;
}
return slenmax;
}
}
运行时可以通过,但是在提交时出现超时(思路比较简单,因而时间复杂度相应会比较高)
clean Code:
public class Solution {
public int lengthOfLongestSubstring(String s) {
boolean[] exist = new boolean[256]; //用表格处理,查找时会很快
int i = 0, maxLen = 0;
for (int j = 0; j < s.length(); j++) {
while (exist[s.charAt(j)]) { //这个while是精髓
exist[s.charAt(i)] = false;
i++;
}
exist[s.charAt(j)] = true;
maxLen = Math.max(j - i + 1, maxLen);
}
return maxLen;
}
}
注:借用了表的形式,把字符串中的字母依次存入表中并进行相应标记(如 exist[s.charAt(i)] = false;)。解决思路是:设定两个指针(i, j),都放在左头开始,j从左到右,遇到有两个相同字母的情况,j停止,计算两相同字母间距,更新最大间距,并且把i 也逐步移到第一个相同字母的下个位置,j再继续移动。
这样时间复杂度为O(n+n)=O(2n);
clean code 2:
public int lengthOfLongestSubstring(String s) {
int[] charMap = new int[256];
Arrays.fill(charMap, -1);
int i = 0, maxLen = 0;
for (int j = 0; j < s.length(); j++) {
if (charMap[s.charAt(j)] >= i) {
i = charMap[s.charAt(j)] + 1;
}
charMap[s.charAt(j)] = j;
maxLen = Math.max(j - i + 1, maxLen);
}
return maxLen;
}
注:用整型表代替布尔型表,时间复杂度降到O(n),原因是在遇到有两个相同字母时没有上面中的 i 逐步移到第一个相同字母下一位置的过程,此处一步到位