zoukankan      html  css  js  c++  java
  • LeetCode OJ: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.

    使用双指针,前一个指针向前走,有不相同的字符的时候标记即可,发现相同时停止,这是后面的字符向后走,直到发现这个字符,然后前指针继续向前走,一直重复直到整个过程的结束,代码如下:

     1 class Solution {
     2 public:
     3     int lengthOfLongestSubstring(string s) {
     4         if(!s.size()) return 0;
     5         int i = 0, j = 1;
     6         int maxSubLen = 1;
     7         bool canUse[256];   //char类型只有256个
     8         memset(canUse, true, sizeof(canUse));
     9         canUse[s[0]] = false;
    10         while(j < s.size()){
    11             if(!canUse[s[j]]){
    12                 maxSubLen = max(maxSubLen, j - i);
    13                 while(i < j){
    14                     if(s[i] != s[j])
    15                         canUse[s[i]] = true, ++i; 
    16                     else{
    17                         i++;
    18                         break;
    19                     }
    20                 }
    21             }else{
    22                 maxSubLen = max(maxSubLen, j - i + 1);
    23                 canUse[s[j]] = false;
    24             }
    25             ++j;
    26         }
    27         return maxSubLen;  
    29     }
    30 };

    写的有点乱啊,见谅见谅。。

  • 相关阅读:
    Solr4.8.0源码分析(12)之Lucene的索引文件(5)
    JAVA基础(1)之hashCode()
    Solr4.8.0源码分析(11)之Lucene的索引文件(4)
    检查数据不一致脚本
    索引的新理解
    数据库放到容器里
    动态规划
    每天晚上一个动态规划
    postgresql parallel join example
    名不正,则言不顺
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4943856.html
Copyright © 2011-2022 走看看