您的位置:首页 > 其它

leetcode@ [30/76] Substring with Concatenation of All Words & Minimum Window Substring (Hashtable, Two Pointers)

2016-02-25 06:04 429 查看
https://leetcode.com/problems/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).

class Solution {
public:
string minWindow(string s, string t) {
if(s.length() == 0 || s.length() < t.length())  return "";
if(s.length() == t.length()) {
if(s == t)  return s;
}

map<char, int> h; h.clear();
map<char, bool> mh; mh.clear();
for(int i=0; i<t.length(); ++i) {
h[t[i]]++;
mh[t[i]] = true;
}

int cnt = t.length(), l = 0, minRange = INT_MAX, mini, minj;
for(int r=0; r<s.length(); ++r) {
if(mh[s[r]]) {
--h[s[r]];
if(h[s[r]] >= 0)  --cnt;
}

if(cnt == 0) {
while(!mh[s[l]] || h[s[l]] < 0) {
++h[s[l]];
++l;
}

if(minRange > r - l + 1) {
minRange = r - l + 1;
mini = l;
}
}
}

if(minRange == INT_MAX)  return "";

return s.substr(mini, minRange);
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: