题目:
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.
代码:
public class Solution {
public int lengthOfLongestSubstring(String s) {
int head = 0, longlenth = 0;
char[] ch = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
int lastIndex = s.indexOf(ch[i], head);
if (head <= lastIndex && lastIndex <= i) {
if (lastIndex != i) {
head = lastIndex + 1;
}
}
longlenth = Math.max(longlenth, i - head + 1);
}
return longlenth;
}
}
PS:由于用的java,时间上有点慢,各种超时,只能慢慢调慢慢优化,最后总算通过了。