您的位置:首页 > 其它

Leetcode[3] Longest Substring Without Repeating Characters

2015-05-07 21:41 351 查看
Given astring, 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.

C++版

class Solution {
public:

int lengthOfLongestSubstring(string s)
{
int n = s.length();
int i=0,j=0;  ///两个指针,i始终指向新的字串开头,j一直往后走.
int maxLen = 0;
bool exist[256] = {false};

for(;j <n ; j++) {
if (exist[s[j]]) {
maxLen = max(maxLen, j-i);
while (s[i] != s[j]) {
exist[s[i]] = false;
i++;
}
i++;

} else {
exist[s[j]] = true;

}
}
return max(maxLen, j-i);
}
};
Java版

public class Solution {
public int lengthOfLongestSubstring(String s) {
boolean[] exist = new boolean[256];
int i = 0, j = 0, maxLen = 0;
for (; j < s.length(); j++) {
while (exist[s.charAt(j)]) {
exist[s.charAt(i)] = false;
i++;
}
exist[s.charAt(j)] = true;
maxLen = Math.max(j - i + 1, maxLen);
}
return maxLen;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: