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;
        }
    };
    
  • 相关阅读:
    二分图的最大匹配
    染色法判定二分图
    kruskal求最小生成树
    prim算法求最小生成树
    floyd
    spfa算法
    bellman_ford
    Dijkstra
    文件操作_1-18 选择题
    会话控制_2-5 编程练习
  • 原文地址:https://www.cnblogs.com/xingxing1024/p/7504329.html
Copyright © 2011-2022 走看看