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;
        }
    };
  • 相关阅读:
    kafka概述
    Spark网络通信分析
    spark序列化及MapOutputTracker解析
    spark checkpoint详解
    深入理解spark streaming
    spark Listener和metrics实现分析
    Spark SQL catalyst概述和SQL Parser的具体实现
    spark block读写流程分析
    java 分布式实践
    单元测试ppt
  • 原文地址:https://www.cnblogs.com/yatesxu/p/5547539.html
Copyright © 2011-2022 走看看