zoukankan      html  css  js  c++  java
  • [leetcode] Longest Substring Without Repeating Characters

    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.
     
    思路:
    max = 0
    s = "abcabcbb";
    sub = "";
    1, sub = a;   max = 1;
    2, sub = ab;   max = 2;
    3, sub = abc;  max = 3;
    4, sub = bca;    max = 3;
    5, sub = cab;    max = 3;
    6, sub = abc;    max = 3;
    7, sub = cb;(因为abc中含有b,所以新的子串为原来子串b之后的字符串加上重复的那个字符,及取abc的c字符串加上重复的那个字符b,构成新的sub字符串cb)  max = 3;
    8, sub = b;(理由同上) max = 3;
     
     1 class Solution
     2 {
     3 public:
     4   int lengthOfLongestSubstring(string s)
     5   {
     6     int max = 0;
     7     string sub = "";
     8 
     9     for(int i = 0; i < s.size(); i++)
    10     {
    11       if(string::npos == sub.find(s[i]))
    12         sub += s[i];
    13       else
    14         sub = sub.substr(sub.find(s[i]) + 1) + s[i];
    15 
    16       max = max >= sub.length() ? max : sub.length();
    17     }
    18     return max;
    19   }
    20 };
  • 相关阅读:
    网络流 讲解
    二分图判定 【模板】
    POJ——T3352 Road Construction
    shell脚本编写-自动部署及监控
    万能头文件
    1284 2 3 5 7的倍数(容斥原理)
    1289 大鱼吃小鱼(栈)
    1305 Pairwise Sum and Divide(数学 ,规律)
    博客达人
    Prim算法---最小生成树
  • 原文地址:https://www.cnblogs.com/lxd2502/p/4316081.html
Copyright © 2011-2022 走看看