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:

  • 相关阅读:
    async await 了解
    vi 命令
    mysql 相关操作
    mac下配置python的虚拟环境virtualenv和虚拟环境管理包virtualenvwrapper
    ip 域名 和端口号
    脱离 flask 上下文,使用 jinja2 来动态渲染模板
    使用 vue-cli 3.0 创建项目
    p 标签和 span 标签
    el-table 更改表格行高和列髋
    使用 axios 传参问题
  • 原文地址:https://www.cnblogs.com/freeneng/p/3096508.html
Copyright © 2011-2022 走看看