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

这道题找字符串中不重复字符的最长子串长度,难度为Medium。

  • 首先想到的是用HashTable。从字符串头部开始计算子串,将没有重复出现的字符存入HashTable中,如果遇到相同的字符,表明当前不重复子串已经结束,从HashTable中查到的重复字符位置开始重新计算子串,比较确定此子串是否是当前最长的,遍历整个字符串后得到不重复字符的最长子串长度。具体代码:
    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            unordered_map<char, int> hash;
            int maxLen = 0;
            int pos = -1;
            
            for(int i=0; i<s.size(); i++) {
                auto it = hash.find(s[i]);
                if((it != hash.end()) && (it->second >= pos)) {
                    pos = it->second;
                }
                hash[s[i]] = i;
                maxLen = max(maxLen, i-pos);
            }
            
            return maxLen;
        }
    };
  • 通过之后查看了别人的代码,发现有不用HashTable的方法,非常巧妙,用字符ascii码做下标把字符位置存入vector中,避免使用HashTable,效率上有所提高,复制其代码供大家参考:
    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;
        }
    };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值