首页 > 代码库 > [LintCode] Longest Substring Without Repeating Characters
[LintCode] Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Have you met this question in a real interview?
Yes
Example
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
.
Challenge
O(n) time
LeetCode上的原题,请参见我之前的博客Longest Substring Without Repeating Characters。
解法一:
class Solution {public: /** * @param s: a string * @return: an integer */ int lengthOfLongestSubstring(string s) { int res = 0, left = -1; vector<int> m(256, -1); for (int i = 0; i < s.size(); ++i) { left = max(left, m[s[i]]); m[s[i]] = i; res = max(res, i - left); } return res; }};
解法二:
class Solution {public: /** * @param s: a string * @return: an integer */ int lengthOfLongestSubstring(string s) { int res = 0, left = 0, right = 0; unordered_set<char> st; while (right < s.size()) { if (!st.count(s[right])) { st.insert(s[right++]); res = max(res, (int)st.size()); } else { st.erase(s[left++]); } } return res; }};
[LintCode] Longest Substring Without Repeating Characters
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。