【Substring with Concatenation of All Words】cpp

题目:

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

代码:

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
            vector<int> ret;
            if ( words.empty() || s.empty() ) return ret;
            const int len_w = words[0].size();  // length of substring in words
            const int end = words.size()*len_w; // total length of words
            if ( end>s.size() ) return ret;     // s size not enough
            map<string, int> ori;
            for ( int i=0; i<words.size(); ++i )
            {
                if ( ori.find(words[i])==ori.end() ){
                    ori[words[i]] = 1;
                }
                else{
                    ori[words[i]]++;
                }
            }
            map<string, int> found;
            int match_num = 0;
            int begin = 0;
            int i = 0;
            while ( i<s.size() )
            {
                //cout << "i:" << i << endl;
                //cout << "m:" << match_num << endl;
                //cout << "begin:" << begin << endl;
                // match one substring in words
                if ( ori.find(s.substr(i,len_w))!=ori.end() )
                {
                    found[s.substr(i,len_w)]++;
                    // substring occur more than times in words
                    if ( found[s.substr(i,len_w)]>ori[s.substr(i,len_w)] )
                    {
                        found.clear();
                        match_num = 0;
                        begin++;
                        i=begin;
                        continue;
                    }
                    i = i+len_w;
                    match_num++;
                    //cout << match_num << endl;
                    // match all substrings in words and push back a starting indices
                    if ( match_num==words.size() )
                    {
                        ret.push_back(i-end);
                        found.clear();
                        begin++;
                        i = begin;
                        match_num=0;
                    }
                }
                // not match
                else
                {
                    found.clear();
                    match_num = 0;
                    begin++;
                    i=begin;
                }
            }
            return ret;
    }
};

tips:

采用双指针技巧。

维护几个关键变量:

1. begin:可能的有效开始位置

2. match_num: 已经匹配上的words中的个数

3. ori: words中每个string,及其出现的次数

4. found: 当前已匹配的interval中,words中每个string,及其出现的次数

思路就是如果找到了匹配的某个string,i就不断向后跳;跳的过程中可能有两种情况不能跳了:

a) 下一个固定长度的子字符串不匹配了

b) 下一个固定长度的子字符串虽然匹配上了words中的一个,但是匹配的数量已经超过了ori中该string的数量

如果一旦不能跳了,就要把match_num和found归零;而且需要回溯到begin++的位置,开始新一轮的搜寻。

这里有个细节要注意:

直接用found.clear()就可以了,如果一个一个清零,会超时。

时间: 2024-12-28 15:52:43

【Substring with Concatenation of All Words】cpp的相关文章

【Remove Duplicates from Sorted Array II】cpp

题目: Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For example,Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]. 代码: class Solution { public: int removeDuplic

【Flatten Binary Tree to Linked List】cpp

题目: Given a binary tree, flatten it to a linked list in-place. For example,Given 1 / 2 5 / \ 3 4 6 The flattened tree should look like: 1 2 3 4 5 6 代码: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNo

【Remove Duplicates from Sorted List II 】cpp

题目: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. For example,Given 1->2->3->3->4->4->5, return 1->2->5.Given 1->1->1->2->3, return 2->

【Binary Tree Level Order Traversal II 】cpp

题目: Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example:Given binary tree {3,9,20,#,#,15,7}, 3 / 9 20 / 15 7 return its bottom-up level order tr

【Binary Tree Zigzag Level Order Traversal】cpp

题目: Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example:Given binary tree {3,9,20,#,#,15,7}, 3 / 9 20 / 15 7 return its

【Kth Smallest Element in a BST 】cpp

题目: Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Note: You may assume k is always valid, 1 ≤ k ≤ BST's total elements. Follow up:What if the BST is modified (insert/delete operations) often and you

【Letter Combinations of a Phone Number】cpp

题目: Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:Digit string "23" Output: ["ad", "ae"

【leetcode刷题笔记】Substring with Concatenation of All Words

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

【leetcode】Substring with Concatenation of All Words

Substring with Concatenation of All Words You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any interv