LeetCode (33) Longest Substring Without Repeating Characters
2015-05-07 14:49
423 查看
题目描述
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.
解题思路
如下图所示:左侧为遍历字符串操作,当遇到重复的字符串时,得到的新的substring为重复字符串后面部分的字符串与被遍历到的字符串相连部分。例如当”abc”遍历到第四号位的’a’时,原substring中的”bc”被保留,并与新的字符串相连。代码
class Solution { public: int lengthOfLongestSubstring(string s) { if (s.size() == 1 || !s.size()) return s.size(); string sub; int max = 0; for (size_t i = 0; i != s.size(); ++i) { char c = s[i]; if (sub.find(c) != string::npos) { max = max > sub.size() ? max : sub.size(); int idx = sub.find(c); sub = sub.substr(idx + 1); } sub.append(1, c); } max = max > sub.size() ? max : sub.size(); return max; } };
相关文章推荐
- 【LeetCode】Longest Substring Without Repeating Characters
- LeetCode之3. Longest Substring Without Repeating Characters
- [LeetCode]Longest Substring Without Repeating Characters
- LeetCode java Longest Substring Without Repeating Characters
- 3. [leetcode] Longest Substring Without Repeating Characters
- [LeetCode]Longest Substring Without Repeating Characters
- LeetCode3 Longest Substring Without Repeating Characters
- LeetCode题解——Longest Substring Without Repeating Characters
- LeetCode 3 Longest Substring Without Repeating Characters
- LeetCode: Longest Substring Without Repeating Characters (3)
- [LeetCode] Longest Substring Without Repeating Characters [15]
- LeetCode:Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- [LeetCode]-algorithms-Longest Substring Without Repeating Characters
- [LeetCode] 046: Longest Substring Without Repeating Characters
- leetcode-Longest Substring Without Repeating Characters
- [LeetCode]Longest Substring Without Repeating Characters
- LeetCode 003-Longest Substring Without Repeating Characters
- LeetCode(3) Longest Substring Without Repeating Characters
- leetcode第3题——**Longest Substring Without Repeating Characters