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.

    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.

    思路

    采用哈希的思想,建立数组,映射字符串,记录字符串每个字符出现的位置。

    最长无重复子串肯定包含在两个重复字符之间,或者,没有重复时,从头到尾。

    遇到重复字符(哈希数组中记录了一个位置),更新起始位置。

    每前进一个位置,将最大值与当前位置与起始位置的差比较更新最大值。

    代码

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            vector<int> dict(256, -1);
            int maxLen = 0, start = -1;
            for (int i = 0; i != s.length(); i++) {
                if (dict[s[i]] > start)
                    start = dict[s[i]];
                dict[s[i]] = i;
                maxLen = max(maxLen, i - start);
            }
            return maxLen;
        }
    };
  • 相关阅读:
    idea 缺失右侧maven窗口
    SpringCloud
    Java面试题——Java基础
    json对象、json字符串的区别和相互转换
    java中的 private Logger log=Logger.getLogger(this.getClass());
    http网络编程
    ansible和helm
    template模板
    http中get和post请求方式
    session和cookie
  • 原文地址:https://www.cnblogs.com/yatesxu/p/5547539.html
Copyright © 2011-2022 走看看