zoukankan      html  css  js  c++  java
  • Leetcode 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.

    题目的意思:输入一个字符串,求不含有重复字母的最长子串的长度

    本题用哈希表的键值记录字母和字母的位置,为了记录长度,需要最长子串的开始位置。

    每当扫描字符串的字符时,如果该字符已经出现过,而且现在的位置在开始位置之后,更新开始位置。

    然后更新哈希表的值,并且保存最长子串的长度。

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            unordered_map<char,int> hash_map;
            int maxLen = 0,start = 0;
            for(int i = 0; i < s.length(); ++ i){
                if(hash_map.find(s[i])!=hash_map.end() && hash_map[s[i]] >=start){
                    start = hash_map[s[i]]+1;
                }
                hash_map[s[i]] = i;
                maxLen = max(maxLen,i-start+1);
            }
            return maxLen;
        }
    };
  • 相关阅读:
    Alpha冲刺
    Alpha冲刺
    抽奖系统(记一次未完成的教训)
    Alpha冲刺
    软件工程
    软工实践
    软工实践
    软工实践
    软工实践
    软工实践
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3824094.html
Copyright © 2011-2022 走看看