题目地址 点击打开链接
题目描述:
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.
代码:
- class Solution {
- public:
- int lengthOfLongestSubstring(string s)
- {
- int index = 0;
- int max = 0;
- int len = s.length();
- if( len == 0)
- return 0;
- if (len ==1)
- return 1;
- for (int i =1; i< len; i++)
- {
- for(int j=i-1; j>=index; j--)
- {
- if(s[i] == s[j])
- {
- index = j+1;
- break;
- }
- else
- {
- if(max < i-j+1)
- max = i - j +1;
- }
- }
- }
- return max;
- }
- };
附送大神代码 :
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> dict(256, -1);
int maxLen = 0, start = -1;
for (int i = 0; i != s.length(); i++) {
if (dict[s[i]] > start)
start = dict[s[i]];
dict[s[i]] = i;
maxLen = max(maxLen, i - start);
}
return maxLen;
}
};
本文介绍了一种解决LeetCode上经典字符串问题的方法——寻找给定字符串中最长的无重复字符子串。通过双指针技术和哈希表,实现了一个高效的解决方案,并提供了易于理解的代码示例。
701

被折叠的 条评论
为什么被折叠?



