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;
        }
    };
    
  • 相关阅读:
    1062 Talent and Virtue (25 分)
    1083 List Grades (25 分)
    1149 Dangerous Goods Packaging (25 分)
    1121 Damn Single (25 分)
    1120 Friend Numbers (20 分)
    1084 Broken Keyboard (20 分)
    1092 To Buy or Not to Buy (20 分)
    数组与链表
    二叉树
    时间复杂度与空间复杂度
  • 原文地址:https://www.cnblogs.com/xingxing1024/p/7504329.html
Copyright © 2011-2022 走看看