Leetcode题目3: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.
寻找最长不重复子串,我的思路是:循环整个字符串,开始位置start到结束位置end(不包含)是无重复的子串,其长度记录在cur_len变量中,根据这个cur_len更新最长子串长度值Length,在[start,end)区间中搜索s.charAt[end]字符返回index:
1)如果找到,说明[start,end]区间有重复元素,位置在index处,然后更新最长长度Length和cur_len的值,此处最易出错:下次查找区间为[index+1, end+1], 该区间长度为end - index;根据这个值更新cur_len;
2)如果未找到,更新cur_len和end即可;
最后循环结束后需要再次判断cur_len值和Length来决定最终的结果;这个地方也容易忽略;
public class Solution {
public int lengthOfLongestSubstring(String s) {
int length = 0; //length of the longest substring
int temp_len = 0; //length for temp
int cur_len = 0; //length of the current substring
int start = 0; //start of the searching
int end = 0; //end of the searching
int index;
for (; end < s.length();) {
//更新最长子串长度
if (cur_len > length) {
length = cur_len;
}
index = find(s, s.charAt(end), start, end);
//如果是重复元素,则确定下次搜索的区间,并更新length和cur_len值
//如果不是重复元素,则更新当前长度和下个搜索元素
if (index != -1) {
temp_len = end - index;
if (temp_len > length) {
length = temp_len;
}
cur_len = temp_len;
start = index + 1;
++end;
} else {
++cur_len;
++end;
}
}
//确定最终返回值
if (cur_len > length) {
return cur_len;
}
return length;
}
/**
* 在字符串s的[start, end)区间寻找ch字符,找到则返回下标,否则返回-1
*/
public int find(String s, char ch, int start, int end) {
for (; start < end; ++start) {
if (s.charAt(start) == ch) {
return start;
}
}
return -1;
}
}