原题如下:
1377. Find Substring
Given the length k, find all substrings of length k in the string str.The characters of a substring can not be repeated and output the number of substrings that satisfy such conditions (the same substring is counted only 1 times).
Example
Given str = “abc”, k = 2, output 2.
Explanation:
Characters are not repeated, and substrings of length k have “ab”, “bc”.
Given str = “abacb”, k = 1, output 3.
Explanation:
Characters are not repeated, and substrings of length k have “a”, “b”.”c”.
Notice
|str| <= 100000.
k <= 100000.
All characters are lowercase.
解法1:
我的解法是利用set的去重性。这题可以用2个set,一个去掉重复的string,一个去掉重复的char。我用的一个dup[26]来去重char,速度会稍快一点。
代码同步在
https://github.com/luqian2017/Algorithm
class Solution {
public:
/**
* @param str: The string
* @param k: The length of the substring
* @return: The answer
*/
int findSubstring(string &str, int k) {
int len = str.size();
set<string> ss;
int upperBound = len - k;
for(int i = 0; i <= upperBound; ++i) {
string sub_str = str.substr(i, k);
if (check(sub_str)) {
ss.insert(sub_str);
}
}
return ss.size();
}
private:
bool check(string &str) {
vector<bool> dup(26, false);
int len = str.size();
for (int i = 0; i < len; ++i) {
int index = str[i] - 'a';
if (dup[index]) return false;
dup[index] = true;
}
return true;
}
};