zoukankan      html  css  js  c++  java
  • Longest Substring Without Repeating Characters-----LeetCode

    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.

    解题思路:

    历遍字符串,当当前字符出现过的时候,子串开始位置+1,否则更新locs数组中的hash值为当前位置。

    详细解释参考http://blog.csdn.net/pickless/article/details/9018575

    以下是代码:

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            int locs[256];//保存字符上一次出现的位置
            memset(locs, -1, sizeof(locs));
    
            int idx = -1, max = 0;//idx为当前子串的开始位置-1
            for (int i = 0; i < s.size(); i++)
            {
                if (locs[s[i]] > idx)//如果当前字符出现过,那么当前子串的起始位置为这个字符上一次出现的位置+1
                {
                    idx = locs[s[i]];
                }
    
                if (i - idx > max)
                {
                    max = i - idx;
                }
    
                locs[s[i]] = i;
            }
            return max;
        }
    };
  • 相关阅读:
    大于00
    today
    10
    面试题flask
    开发者日志
    7月22日一天学的东西
    资料
    3333
    2222
    1
  • 原文地址:https://www.cnblogs.com/dollarzhaole/p/3155712.html
Copyright © 2011-2022 走看看