3. Longest Substring Without Repeating Characters
来源:互联网 发布:阿里云域名过户怎么过 编辑:程序博客网 时间:2024/05/22 08:15
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) { if (s == "") return 0; int maxLen = 0, index = 0, subLen = 0; string sub = ""; while (index != s.size()) { if (sub == "" || sub.find(s[index]) == sub.npos) { sub += s[index]; index++; //这里要用subLen记录子串的长度(若不记录,则“c”,"abc"这样的样例会出错) subLen++; } else if (sub.find(s[index]) != sub.npos) { if (sub.size() > maxLen) { maxLen = sub.size(); } int i = index - 1; while (i >= 0) { if (s[i] == s[index]) { index = i + 1; break; } i--; } //一定要把sub和subLen重置 sub = ""; subLen = 0; } } return maxLen > subLen ? maxLen : subLen ; }};
再贴一个别人写的简洁操作:
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; }
阅读全文
0 0
- [LeetCode]3.Longest Substring Without Repeating Characters
- LeetCode 3.Longest Substring Without Repeating Characters
- LeetCode --- 3. Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- [Leetcode] 3. Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters
- [leetcode] 3.Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- [leetcode] 3. Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters
- [Leetcode]3. Longest Substring Without Repeating Characters
- leetcode 3. Longest Substring Without Repeating Characters
- 【Leetcode】3. Longest Substring Without Repeating Characters
- rapidjson使用总结
- gradle android的依赖配置dependencies
- OpenResty 最佳实践学习--安装和helloworld(1)
- 泛型(Generics)
- 【Python】【matplotlib】绘图函数
- 3. Longest Substring Without Repeating Characters
- URI和URL的区别(转自: I'M G.Shine)
- Oil Deposits (简单深搜)积水问题
- 区域外点击执行函数
- SQL Server学习笔记1:如何使用软件以及创建第一个数据库
- 感知机
- POJ2318 计算几何简单题
- 第4周项目4- 建设双链表算法库(选做)
- cocos2dx-lua在ios上实现生成及扫描二维码