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:

  • 相关阅读:
    UARTRS232与RS485的关系
    RS-485总线通信协议
    【转】TCP(协议号6)的方方面面
    【转】Android 编程下的代码混淆
    【转】阻塞与非阻塞socket的优缺点
    【转】Socket状态变迁图
    【转】Spring中IoC的优点与缺点
    linux_UAPI_转
    数组初始化
    中兴被制裁:到底对谁说话 13亿人民中1人有话说
  • 原文地址:https://www.cnblogs.com/freeneng/p/3096508.html
Copyright © 2011-2022 走看看