zoukankan      html  css  js  c++  java
  • 3. Longest Substring Without Repeating Characters

    3. Longest Substring Without Repeating Characters

    Description

    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.

    思路

    我们可以采取扫描法。 刚开始将i, j指针指向位置0,然后往后移动j指针直到序列出现重复,此时更新答案,完后移动i指针使得[i, j)区间内没有重复,继续上述操作。

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            int res = 0;
            int count[300];
            memset(count, 0, sizeof(count));
            int i=0, j=0;
            while(1) {
                while(count[s[j]] == 0 && j<s.length()) {
                    count[s[j]]++;
                    j++;
                }
                res = max(res, j-i);
                if(j == s.length()) break;
                while(s[i] != s[j]) {
                    count[s[i]]--;
                    i++;
                }
                count[s[i]]--;
                i++;
            }
            return res;
        }
    };
    
  • 相关阅读:
    noip2018练习总结
    东方CannonBall (概率DP)
    数论
    逆序对
    USACO5.3 校园网Network of Schools(Tarjan缩点)
    USACO09FEB 改造路Revamping Trails(分层图模板)
    Comet OJ模拟赛 Day1
    Tarjan模板
    NOIP 天天爱跑步(树上差分)
    树上差分
  • 原文地址:https://www.cnblogs.com/xingxing1024/p/7504329.html
Copyright © 2011-2022 走看看