字符串 Substring with Concatenation of All Words

来源:互联网 发布:灯光设计软件 编辑:程序博客网 时间:2024/05/25 08:12

思想:给定s,找符合条件的串s',该s'包括给定words中的每一个word且仅包含1次,不包含其他字符,返回若干个s'的起始位置。


学习unordered_map:

unordered_map是一种无序的、键值对应的哈希容器。

允许通过key快速索引value,不允许多个value对应到同一个key。

构造函数:unordered_map(unordered_map t)

erase函数:

by position (1)

iterator erase ( const_iterator position );
by key (2)
size_type erase ( const key_type& k );
range (3)
iterator erase ( const_iterator first, const_iterator last );

find函数:

Get iterator to element
Searches the container for an element with k as key and returns an iterator to it if found, otherwise it returns an iterator to unordered_map::end (the element past the end of the container).

迭代器的使用:

Iterators of a unordered_map container point to elements of this value_type. Thus, for an iterator called it that points to an element of a map, its key and mapped value can be accessed respectively with:

1234
unordered_map<Key,T>::iterator it;(*it).first;             // the key value (of type Key)(*it).second;            // the mapped value (of type T)(*it);                   // the "element value" (of type pair<const Key,T>) 


Naturally, any other direct access operator, such as -> or [] can be used, for example:
12
it->first;               // same as (*it).first   (the key value)it->second;              // same as (*it).second  (the mapped value) 



class Solution {public:    vector<int> findSubstring(string s, vector<string>& words) {        size_t wordLength = words.front().length();        size_t catLength = words.size()*wordLength;        vector<int> res;        if(s.length() < catLength) return res;        unordered_map<string, int> wordCount;        for(auto word : words) {            wordCount[word]++;        }        for(auto i=s.begin(); i <= prev(s.end(), catLength); i++) {            unordered_map<string, int> unused(wordCount);            for(auto j = i; j != next(i,catLength); j+=wordLength) {                auto pos = unused.find(string(j, next(j,wordLength)));                if(pos == unused.end() || pos->second == 0) break;                pos->second--;                if(pos->second == 0) unused.erase(pos);            }            if(unused.size() == 0) res.push_back(distance(s.begin(), i));        }        return res;            }};


0 0