最长无重复字符的子串-LintCode
2017-10-02 16:15
330 查看
给定一个字符串,请找出其中无重复字符的最长子字符串。
样例:
例如,在”abcabcbb”中,其无重复字符的最长子字符串是”abc”,其长度为 3。
对于,”bbbbb”,其无重复字符的最长子字符串为”b”,长度为1。
挑战 :
O(n) 时间
思路:
遍历字符串,对于每个字符计算长度和起始位置,若在已遍历的字符串中不存在,则起始位置不变,直接计算长度;若在已遍历的字符串中存在,更新起始位置,计算长度,最终取最大长度。
样例:
例如,在”abcabcbb”中,其无重复字符的最长子字符串是”abc”,其长度为 3。
对于,”bbbbb”,其无重复字符的最长子字符串为”b”,长度为1。
挑战 :
O(n) 时间
思路:
遍历字符串,对于每个字符计算长度和起始位置,若在已遍历的字符串中不存在,则起始位置不变,直接计算长度;若在已遍历的字符串中存在,更新起始位置,计算长度,最终取最大长度。
#ifndef C384_H #define C384_H #include<iostream> #include<vector> #include<map> using namespace std; class Solution { public: /* * @param s: a string * @return: an integer */ int lengthOfLongestSubstring(string &s) { // write your code here if (s.empty()) return 0; int res = 0; int start = 0; map<char, int> m; for (int i = 0; i < s.size();++i) { if (m.find(s[i]) == m.end()) { m[s[i]] = i; } else { start = maxVal(m.find(s[i])->second+1,start); m.find(s[i])->second = i; } res = maxVal(res, i - start + 1); } return res; } int maxVal(int a, int b) { return a > b ? a : b; } }; #endif
相关文章推荐
- LintCode-最长无重复字符的子串
- lintcode(384)最长无重复字符的子串
- lintcode,最长无重复字符的子串
- lintcode-384-最长无重复字符的子串
- [Lintcode] Longest Substring Without Repeating Characters 最长无重复字符的子串
- [LintCode 384] 最长无重复字符的子串(Python)
- LintCode 最长无重复字符的子串
- 最长无重复字符的子串 lintcode
- lintcode: 最长无重复字符的子串
- 3.无重复字符的最长子串(Longest Substring Without Repeating Characters)
- 符串的最长无重复字符的子串长度
- C++找出字符串中最长的不含重复字符的子串
- [leetcode]获取字符串中字符不重复的最长子串的长度
- [leetcode]无重复字符的最长子串
- 求字符串中不含重复字符的最长子串的长度
- 无重复字符的最长子串
- 找到字符串的最长无重复字符子串
- 求字符串中最长无重复字符的子串
- c 求字符串内无重复字符的最长子串
- 求一字符串最长不重复字符子串的长度【Java 版】