您的位置:首页 > 其它

Two pointers (7) -- Longest Substring Without Repeating Characters, Substring with Concatenation of

2017-01-23 11:03 381 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode