Two pointers (7) -- Longest Substring Without Repeating Characters, Substring with Concatenation of

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.


1. DP。有的答案说使用双指针,其实没有必要,我们只要记录子串的长度就好了。

2. 包含每个字符的最长子串长度为  dp = min(dp + 1, i - lastIndex);  

3. 相比使用unordered_map,使用vector在查询的时候会更快一些

    int lengthOfLongestSubstring(string s) {
        vector<int> cmap(256, -1);
        int dp = 0;
        int maxLen = 0;
        for (int i = 0; i < s.size(); i++){
            int lastIndex = cmap[s[i]];
            dp = min(dp + 1, i - lastIndex);  //lastIndex为该字符上次出现的位置
            maxLen = max(maxLen, dp);
            cmap[s[i]] = i;
        }
        return maxLen;
    }



Substring with Concatenation of All Words

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

For example, given:
s"barfoothefoobarman"
words["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).


使用map记录words中每个word出现的次数;然后使用长度为totalLen的滑动窗口,判断子串是否包含所有word。

    bool valid(unordered_map<string, int> smap, string s, int wLen){
        for (int i = 0; i < s.size(); i += wLen){
            string subs = s.substr(i, wLen);
            if (smap.find(subs) == smap.end() || smap[subs] == 0)  //word不存在或者已经用完
                return false;
            else smap[subs]--;
        }
        return true;
    }
    
    vector<int> findSubstring(string s, vector<string>& words) {
        if (words.empty()) return vector<int>();
        int wLen = words[0].size();
        int totalLen = words.size() * wLen;  //words中所有word的总长度
        if (s.size() < totalLen) return vector<int>();
        
        vector<int> rst;
        unordered_map<string, int> smap;
        for (string w: words){   //统计word的个数
            smap[w]++;
        }
        for(int i = 0; i <= s.size() - totalLen; i++){
            if (valid(smap, s.substr(i, totalLen), wLen))
                rst.push_back(i);
        }
        return rst;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值