• leetcode 3. Longest Substring Without Repeating Characters


    Given a string, find the length of the longest substring without repeating characters.

    Example 1:

    Input: "abcabcbb"
    Output: 3 
    Explanation: The answer is "abc", with the length of 3. 
    

    Example 2:

    Input: "bbbbb"
    Output: 1
    Explanation: The answer is "b", with the length of 1.
    

    Example 3:

    Input: "pwwkew"
    Output: 3
    Explanation: The answer is "wke", with the length of 3. 
                 Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
     1 class Solution {
     2 public:
     3     int lengthOfLongestSubstring(string s) {
     4         int i = 0, j = 0;
     5         map<char, int> mp; //值映射的是字符所在的下标位置
     6         int len = s.length(); //字符串的长度
     7         vector<int> dp(len, 0); //dp[j]表示以第j个字符结尾的不重复子串的长度
     8         int maxn = 0;
     9         for (j = 0; j < len; j++) {
    10             //如果当前的字符已经之前出现过了,并且是在i之后位置的,那么要更新窗口左边的下标
    11             if (mp.count(s[j]) > 0) { 
    12                 i = max(i, mp[s[j]] + 1);
    13             }
    14             dp[j] = j - i + 1; //窗口大小即为以第j个字符结尾的最长不重复子串的长度
    15             mp[s[j]] = j;
    16             maxn = max(maxn, dp[j]);
    17         }
    18         return maxn;
    19     }
    20 };
  • 相关阅读:
    python基础之元组,集合
    python列表补充、循环
    python基础之字典、赋值补充
    python基础2
    基本数据类型
    计算机基础与计算机硬件总结
    python基础
    操作系统
    Django APP打包重用
    PyCharm 使用Github托管Django项目
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/11432781.html
Copyright © 2020-2023  润新知