zoukankan      html  css  js  c++  java
  • 3. Longest Substring Without Repeating Characters

    Question:

    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

    Solution 1:

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
    
            vector<int> dict(256,-1);    //用Ascll码来作为key, 该位无值事默认为-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;
        }
    };
    

    Solution 2: 思路类似。

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
    		int maxLen = 0, start = -1;
    		unordered_map <char, int> hashMap;
    		for(int i = 0; i < s.length(); i++)
    		{
    			if (hashMap.find(s[i]) != hashMap.end())
    			{
    				start = hashMap[s[i]] > start? hashMap[s[i]]:start;
    			}
    			hashMap[s[i]] = i;
    			maxLen = max(maxLen, i - start);
    		}
            return maxLen;
        }
    };
    

    题目地址

  • 相关阅读:
    Python SOCKET网络编程
    网络基础 -- 子网划分
    网络基础 -- 网络协议篇
    面向对象练习:学生选课系统
    python 异常处理 断言
    Python 面向对象 中高级
    Python 面向对象 基础
    Python 练习
    Python 练习计算器
    Python 正则表达式
  • 原文地址:https://www.cnblogs.com/Pomelos/p/15681318.html
Copyright © 2011-2022 走看看