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 };

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

  • 相关阅读:
    软件工程
    ROR
    全息技术(Holographic technique)
    VR技术、AR技术、MR技术
    人工智能(AI)
    机器学习(Machine Learning)
    hdoj Scaena Felix
    周赛题解
    Good Luck in CET-4 Everybody!(博弈)
    Paths on a Grid(规律)
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4943856.html
Copyright © 2011-2022 走看看