zoukankan      html  css  js  c++  java
  • 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.

    思路:

    使用一个map保存字母和序号的对应关系。从前往后扫描字符串,如果map里没有保存当前字母,就将该字母和它在原字符串中的序号存到map;否则先判断下map中的字母数是否大于最大值,如果大于的话更新最大值,然后将该字母以及它之前的字母从map中删除,继续扫描。

    代码:

     1     int lengthOfLongestSubstring(string s) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         map<char, int> visited;
     5         int l = s.length();
     6         if(l == 0)
     7             return 0;
     8         int result = 1, tmp, last = 0;
     9         for(int i = 0; i < l; i++){
    10             if(visited.find(s[i]) == visited.end()){
    11                 visited[s[i]] = i;
    12             }
    13             else{
    14                 tmp = visited.size();
    15                 if(tmp > result){
    16                     result = tmp;
    17                 }
    18                 tmp = visited[s[i]]+1;
    19                 for(int j = last; j <= visited[s[i]]; j++){
    20                     visited.erase(s[j]);
    21                 }
    22                 last = tmp;
    23                 visited[s[i]] = i;
    24             }
    25         }
    26         tmp = visited.size();
    27         if(tmp > result)
    28             result = tmp;
    29         return result;
    30     }

     第二遍

     1     int lengthOfLongestSubstring(string s) {
     2         int len = s.length();
     3         if(len == 0)
     4             return 0;
     5         int place[256];
     6         for(int i = 0; i < 256; i++)
     7             place[i] = -1;
     8         int maxLen = INT_MIN;
     9         int begin = 0, end = 0;
    10         while(end < len){
    11             if(place[s[end]] == -1){
    12                 place[s[end]] = end;
    13                 end++;
    14             }
    15             else{
    16                 maxLen = max(maxLen, end-begin);
    17                 for(int i = begin; i < place[s[end]]; i++){
    18                     place[s[i]] = -1;
    19                 }
    20                 begin = place[s[end]]+1;
    21                 place[s[end]] = end;
    22                 end++;
    23             }
    24         }
    25         maxLen = max(maxLen, end-begin);
    26         return maxLen;
    27     }
  • 相关阅读:
    hdu1874 畅通工程续
    hdu2544 最短路
    hdu1068 Girls and Boys
    hdu1151 Air Raid
    hdu1150 Machine Schedule
    hdu2063 过山车
    Bootstrap 学习笔记12 轮播插件
    Bootstrap 学习笔记11 按钮和折叠插件
    Bootstrap 学习笔记10 弹出框和警告框插件
    Bootstrap 学习笔记9 标签页和工具提示插件
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3418110.html
Copyright © 2011-2022 走看看