[LintCode] Longest Substring Without Repeating Characters
Posted Grandyang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LintCode] Longest Substring Without Repeating Characters相关的知识,希望对你有一定的参考价值。
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
.
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的主要内容,如果未能解决你的问题,请参考以下文章
lintcode-medium-Longest Increasing Subsequence
lintcode-medium-Longest Consecutive Sequence
[Lintcode]124. Longest Consecutive Sequence/[Leetcode]128. Longest Consecutive Sequence