您的位置:首页 > 其它

leetcode 3. Longest Substring Without Repeating Characters

2016-05-31 09:31 381 查看
题目

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.

思路:利用一个exist数组保存字符是否出现(假设char set是ascii),从前向后遍历数组,如果遇到已存在的字符,应该回退到这个字符上次出现的下一个位置从新开始统计,同时注意exist数组的同步更新。

代码public class Solution {
public int lengthOfLongestSubstring(String s) {
if(s.equals("")){
return 0;
}
int res = 1;
int start = 0;
boolean exist[] = new boolean[128];
for(int i = 0;i < 128; i++){
exist[i] = false;
}
for(int i = 0;i < s.length(); i++){
char c = s.charAt(i);
if(exist[c]){
for(int k = start;k < i; k++){
if(s.charAt(k)==c){
start = k+1;
break;
}
exist[s.charAt(k)] = false;
}
}else{
exist[c] = true;
}
if((i-start+1) > res){
res = i - start + 1;
}
}

return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode