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:

  • 相关阅读:
    segmentation fault(core dumped)
    (LIS LCS 例题)Max Sum Advanced Fruits Super Jumping! Jumping! Jumping!
    几种数学公式(环排列 母函数 唯一分解定理 卡特兰数 默慈金数 贝尔数 那罗延数)
    map set 详解
    算法录 之 二分和三分
    LIS 最长上升子序列 LCS 最长公共子序列 模板
    JAVA 大数据 例题
    Java 实现大数算法
    7 21 第一次团队赛——————写给队友
    离散化+unique()+二分查找
  • 原文地址:https://www.cnblogs.com/freeneng/p/3096508.html
Copyright © 2011-2022 走看看