zoukankan      html  css  js  c++  java
  • [Leetcode 41] 3 Longest Substring Without Repeating Characters

    Problem:

    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.

    Analysis:

    There's a one pass algorithm. With the help of a hash table. We can scan through the given string and hash every character into the hash table.

    If ht[a] == 0, then there is no collision, we increase the current substring length and continue.

    If ht[a] != 0, there is a collision. In such case, we do two things: 1) update the max substring length; 2) adjust the length and substring start index to the right position.

    For 1, we only need to compare the current length with the max length and update max length;

    For 2, we start from the current index, and go through until the current position. Each time we process a character, decrease the current length and increase index. Until we find the collision character or reach the newest character cause the problem. Thus we can have the next substring doesn't have collision. Then repeat.

    Code:

     1 class Solution {
     2 public:
     3     int lengthOfLongestSubstring(string s) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         if (s.size() == 0) return 0;
     7         
     8         char ht[26];
     9         int maxLen = 0, len = 0, idx = 0;
    10         
    11         for (int i=0; i<26; i++)
    12             ht[i] = 0;
    13         
    14         for (int i=0; i<s.size(); i++) {
    15             if (ht[s[i] - 'a'] == 0) {
    16                 ht[s[i] - 'a']++;
    17                 len++;
    18             } else {
    19                 if (len > maxLen)
    20                     maxLen = len;
    21                 
    22                 for (; idx<i; idx++) {    
    23                     if (s[idx] == s[i]) {
    24                         idx++;
    25                         break;
    26                     } else {
    27                         len--;
    28                         ht[s[idx] - 'a']--;
    29                     }
    30                 }
    31             }
    32         }
    33         
    34         if (len > maxLen) maxLen = len;
    35         return maxLen;
    36     }
    37 };
    View Code

    Attention:

  • 相关阅读:
    1040 Longest Symmetric String (25)
    1068 Find More Coins (30)
    1045 Favorite Color Stripe (30)
    1008 数组元素循环右移问题 (20)
    1007. 素数对猜想
    1005. 继续(3n+1)猜想 (25)
    1001. 害死人不偿命的(3n+1)猜想 (15)
    递归经典面试题_ 小例
    简单实现_控制台小时钟
    使用Timer组件_实现定时更改窗体颜色
  • 原文地址:https://www.cnblogs.com/freeneng/p/3096508.html
Copyright © 2011-2022 走看看