您的位置:首页 > 编程语言 > C语言/C++

Leetcode: Longest Substring Without Repeating Characters

2013-12-16 08:30 274 查看
Longest Substring Without Repeating Characters

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.

Idea: The idea of this problem is to check the longest substring (no repeating) for each position, keep track the max length in this process. We need a int character to store the visited information of each character.

class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.size() <= 1) return s.size();
int max_len = 0;
int i=0;
while (i<s.size()) {
int j=i;
vector<int> visited(256, 0);
while (j < s.size()) {
if(visited[s[j]] == 0){
visited[s[j]] = 1;
++j;
}
else
{
break;
}
}
max_len = max(max_len, j-i);
while(s[i] != s[j]) {
++i;
}
++i;
}
return max_len;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息