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. 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.

    input:abcabcbb

    output:abc

    这篇其实我先将字符中的各种字符存在str_map中,然后通过设定初始位子以及各字符的最后出现的位置来判定子串的开始位置和子串的长度。时间复杂度O(n),时间:122ms

    代码如下:

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            map<char, int> str_map;
            int maxlen = 0, flag = -1;
            for (int i = 0; i < s.size(); i++){
                if (!str_map.count(s[i])){
                    str_map.insert(make_pair(s[i], -1));
                }
            }
            for (int i = 0; i < s.size(); i++){
                if (str_map[s[i]]>flag)
                    flag=str_map[s[i]];
                if (i - flag > maxlen)
                    maxlen = i - flag;
                str_map[s[i]] = i;
            }
            return maxlen;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    寒假一:打印沙漏
    秋季学期总结
    三位我尊敬的老师
    自我介绍
    polay计数原理
    2020-2021 ACM-ICPC, Asia Seoul Regional Contest
    2017-2018 ACM-ICPC Northern Eurasia(A.Archery Tournament)
    FTT简单入门板子
    佩尔方程最小解模板
    求组合数
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4394801.html
Copyright © 2011-2022 走看看