3.LongestSubstringWithoutRepeatingCharacters
来源:互联网 发布:淘宝网店衣服货源 编辑:程序博客网 时间:2024/06/13 08:44
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.
(给定一个字符串,找出不包含重复字符的最长字符串子串的长度。)
遍历所有字符串总是最容易想到的方法。
解法一:
#include <unordered_map>#include <algorithm>int LongestSubstringWithoutRepeatingCharacters::lengthOfLongestSubstring1(string s){ int result = 0; for (int i = 0; i < s.length(); i++) { for (int j = i; j < s.length(); j++) { // 判断长度已经子字符串中是否包含重复字符 if ((j - i + 1) > result & isWithoutRepeatingCharacters(s.substr(i, j - i + 1))) { result = j - i + 1; } } } return result;}bool LongestSubstringWithoutRepeatingCharacters::isWithoutRepeatingCharacters(string s){ // 哈希表的方式记录是否有重复字符 unordered_map<int, bool> hash; for (int i = 0; i < s.length(); i++) { if (hash.find(s[i]) != hash.end()) { return false; } else { hash[s[i]] = true; } } return true;}
不用说OJ超时。
解法二:
int LongestSubstringWithoutRepeatingCharacters::lengthOfLongestSubstring2(string s){ // 256个字符的列表,初始化为-1 vector<int> dict(256, -1); int maxLen = 0, start = -1; for (int i = 0; i < s.size(); i++) { if (dict[s[i]] > start) // 遇到重复的字符,重置start start = dict[s[i]]; // 标记该字符在原字符串中的位置到字符列表中,便于计算最长长度 dict[s[i]] = i; maxLen = max(maxLen, i - start); } return maxLen;}
测试代码:
LongestSubstringWithoutRepeatingCharacters longestSubstringWithoutRepeatingCharactersongest; string s = "abcdabcbb"; int result = longestSubstringWithoutRepeatingCharactersongest.lengthOfLongestSubstring2(s); cout << result << "\n"; cout << endl;
1 0
- 3.LongestSubstringWithoutRepeatingCharacters
- leetcode解题方案--003--LongestSubstringWithoutRepeatingCharacters
- LeetCode题库——LongestSubstringWithoutRepeatingCharacters
- LeetCode之路——LongestSubstringWithoutRepeatingCharacters
- 3.SetTimer
- 3. References
- 3. 当事人
- 3.当事人
- 3. 代词
- 3.函数
- 3. 光标
- 3.图像
- 3.类
- 3. 教程
- 3.scaling
- 3.军训
- 3.指针
- 3.继承
- ASCII码表
- LINUX 权限
- QT5入门(1)——基本模块
- Linux下的MongoDB增删改查命令
- Linux命令行的艺术
- 3.LongestSubstringWithoutRepeatingCharacters
- 当任务管理器无法结束进程时,使用cmd强制结束进程
- 虚拟机Nat静态IP设置
- 工厂的设计模式
- BZOJ 2459 [BeiJing2011]神秘好人
- 【Yii系列】错误处理和日志系统
- Java-多线程总结
- Android学习日志——第6天
- 一帮一