zoukankan      html  css  js  c++  java
  • leetcode-【中等题】3. Longest Substring Without Repeating Characters

    题目:

    Given a string, find the length of the longest substring without repeating characters.

    Examples:

    Given "abcabcbb", the answer is "abc", which the length is 3.

    Given "bbbbb", the answer is "b", with the length of 1.

    Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

    链接https://leetcode.com/problems/longest-substring-without-repeating-characters/

    答案:

    参考了这个链接后才明白解题思路,然后依据自己的理解写了代码。

    大致思路是:从当前字符开始,往前看,没有出现过重复字符的字符串

    代码:

     1 #define MAX_LETTER_NUM 255
     2 class Solution {
     3 public:
     4     int lengthOfLongestSubstring(string s) {
     5         if(s.empty())
     6         {
     7             return 0;
     8         }
     9         
    10         bool exist[MAX_LETTER_NUM];
    11         int position[MAX_LETTER_NUM];
    12         int index,rangeIndex;
    13         int maxLen = 0;
    14         int start = 0;
    15         
    16         for(index = 0; index < MAX_LETTER_NUM; ++ index)
    17         {
    18             exist[index] = false;
    19             position[index] = 0;
    20         }
    21         
    22         for(index = 0; index < s.size(); ++ index)
    23         {
    24             if(exist[s[index]])
    25             {
    26                 for(rangeIndex = start; rangeIndex <= position[s[index]]; ++ rangeIndex)
    27                 {
    28                     exist[s[rangeIndex]] = false;
    29                 }
    30                 start = position[s[index]] + 1;
    31                 exist[s[index]] = true;
    32             }else
    33             {
    34                 exist[s[index]] = true;
    35                 maxLen = (maxLen < index - start + 1) ? index - start + 1:maxLen;
    36             }
    37             
    38             position[s[index]] = index;
    39         }
    40         
    41         return maxLen;
    42     }
    43 };
    View Code
  • 相关阅读:
    Thread与Handler
    开始机顶盒的生涯
    解决布局被键盘顶的难题
    自动滚动的Textview
    2-解决粘包问题
    1-socket编程
    zipfile模块
    subprocess模块
    day31-异常处理
    collections模块
  • 原文地址:https://www.cnblogs.com/Shirlies/p/5736696.html
Copyright © 2011-2022 走看看