zoukankan      html  css  js  c++  java
  • 【LeetCode刷题系列

    题目:

    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.
     

    代码(C++实现):

     1 class Solution {
     2 public:
     3     int lengthOfLongestSubstring(string s) 
     4     {
     5         // 定义一个map用来存放整个字符串s
     6         unordered_map<char, int> unmap;
     7         
     8         // tempLength记录每次扫描位置开始的一次统计的最长字符串的长度
     9         int tempLength = 0;
    10         // 众多tempLength中的最大值
    11         int maxLength = 0;
    12         
    13         // 第一层循环:分别以s中的每个字符为基准,进行遍历
    14         for (int j = 0; j < s.size(); j++)
    15         {
    16             // 第二层循环:以当前第一层循环中当前的字符为基准,进行遍历,统计以此字符为基准的tempLength
    17             for (int i = j; i < s.size(); i++)
    18             {
    19                 // 是否tempLength继续增加的条件是,map中没有出现过当前指向的字符
    20                 if (unmap.count(s[i]) == 0)                
    21                 {
    22                     pair<char, int> myshopping(s[i], i);
    23                     // 如果当前的map中无此字符,将当前字符插入到map中
    24                     unmap.insert(myshopping);
    25                     tempLength++;
    26                     maxLength = maxLength > tempLength ? maxLength : tempLength;
    27                 }
    28                 // 当前字符已经在map中了,直接break,并将本次使用的map进行清除操作
    29                 else
    30                 {
    31                     
    32                     tempLength = 0;
    33                     unmap.clear();
    34                     break;
    35                 }
    36 
    37             }
    38         }
    39     
    40         return maxLength;
    41         }
    42 };



  • 相关阅读:
    彻底理解数字图像处理中的卷积-以Sobel算子为例
    CSK & KCF(tracking)
    内积、标量积、点积、点乘
    C++拷贝构造函数详解
    从RGB色转为灰度色算法
    混合高斯背景建模原理及实现
    单高斯背景建模
    计算机视觉目标跟踪的算法分类
    SVM:从理论到OpenCV实践
    HOG特征(Histogram of Gradient)学习总结
  • 原文地址:https://www.cnblogs.com/xuelisheng/p/10771848.html
Copyright © 2011-2022 走看看