代码拉取完成,页面将自动刷新
## 3. Longest Substring Without Repeating Characters
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Example 4:
Input: s = ""
Output: 0
Constraints:
0 <= s.length <= 5 * 104
s
consists of English letters, digits, symbols and spaces.首先想到的是用栈来解决。
vote最多的一个cpp解法:
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;
}
用set来解决:
int lengthOfLongestSubstring(string s) {
int n=s.length();
if(n==0)
return 0;
set<char> st;
int maxsize=0;
int i=0,j=0;
while(j<n)
{
if(st.count(s[j])==0)
{
st.insert(s[j]);
maxsize=max(maxsize,(int)st.size());
j++;
}
else
{
st.erase(s[i]);
i++;
}
}
return maxsize;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。