輸入一個字符串 :
“pwwkew”
輸出:
3
//“wke”
solution
class Solution {
public int lengthOfLongestSubstring(String s) {
int sub = 0;
int before = 0;
for (int i = 0 ; i < s.length() ; ++i) {
int tempIndex = this.indexOf(s, i-before, i, s.charAt(i));
if (tempIndex == -1) {
++before;
} else {
before = i - tempIndex;
}
if (before > sub) {
sub = before;
}
}
return sub;
}
public int indexOf(String s, int begin, int end, int ch) {
for (int i = begin; i < end ; ++i) {
if (s.charAt(i) == ch) {
return i;
}
}
return -1;
}
}
explain:
before是累計找到的不同字符數(shù), 若一直沒找到, 則一直累加
indexof 方法從當(dāng)前位置往前before開始, 找相同的字符
如果找到, 則舍棄找到的位置之前的所有字符,繼續(xù)查重
每次迭代結(jié)尾,在sub中保存目前最長的無重復(fù)子字符串