欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

Two pointers (7) -,twopointers

来源: javaer 分享于  点击 32813 次 点评:157

Two pointers (7) -,twopointers


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;
    }


相关文章

    暂无相关文章

用户点评