字符串 Substring with Concatenation of All Words

思想:给定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:

1
2
3
4
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:
1
2
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;        
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值