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.
package November;
public class LongestSubstringWithoutRepeatingCharacters {
public static int lengthOfLongestSubstring(String s) {
if(s==null||s.isEmpty())
return 0;
int max = 1;
int index = 1;
int sum = 1;
while (index < s.length()) {
int pos=existInSubstring(s,index-sum,index-1,s.charAt(index));
if (pos==-1) {
sum++;
if(sum>max){//这里需要注意,及时更新max值
max=sum;
}
index++;
} else {
if (sum > max) {
max = sum;
}
sum = 1;
index=pos+2;//这里需要注意,回退点不是index+1,而是上一个重复的地方,例如dvdf,应该是3,而不是2
}
}
return max;
}
public static int existInSubstring(String s, int start, int end,
char c) {
for (int index = start; index <= end; index++) {
if (s.charAt(index) == c)
return index;
}
return -1;
}
public static void main(String[] args) {
// String s1 = "abcabcbb";
// String s2 = "bbbbb";
// String s3 = "pwwkew";
String s4="au";
String s5="dvdf";
// System.out.println(lengthOfLongestSubstring(s1));
// System.out.println(lengthOfLongestSubstring(s2));
// System.out.println(lengthOfLongestSubstring(s3));
System.out.println(lengthOfLongestSubstring(s4));
System.out.println(lengthOfLongestSubstring(s5));
}
}