昨天在LeetCode上搞了两题,如下:
Longest Uncommon Subsequence I没啥好说的,水过去
int findLUSlength(string a, string b) {
if (a == b) return -1;
else return a.length()>b.length()? a.length(): b.length();
}
Longest Uncommon Subsequence II
第二题,把第一题省下的时间又搞回去了。。
没啥精妙的套路,暴力求解,有点长。
bool sContainsT(string s, string t) {
bool isContain = false;
int i = 0, j = 0;
while (i < s.length() && j < t.length()) {
if (t[j] == s[i]) {
j++; i++;
}
else
i++;
}
if (j == t.length())
isContain = true;
return isContain;
}
int findLUSlength(vector<string>& strs) {
vector<vector<string> > stringByLenght(11);
set<string> stringSet;
set<string> uniqueStringSet;
set<string>::iterator itr;
int length = 0, currStringLength = 0;
int longest = strs[0].length();
for (size_t i = 0; i < strs.size(); i++) {
stringByLenght[strs[i].length()].push_back(strs[i]);
if (strs[i].length() > longest)
longest = strs[i].length();
}
for (int i = 0; i < stringByLenght[longest].size(); i++) {
if (stringSet.insert(stringByLenght[longest][i]).second == true) {
length += longest;
}
else {
length -= longest;
if (length < 0) length = 0;
}
}
if (length > 0)
return longest;
else
length = -1;
currStringLength = longest - 1;
while (currStringLength > 0 && length == -1) {
uniqueStringSet.clear();
for (int i = 0; i < stringByLenght[currStringLength].size(); i++) {
if (stringSet.insert(stringByLenght[currStringLength][i]).second == true)
uniqueStringSet.insert(stringByLenght[currStringLength][i]);
else
uniqueStringSet.erase(stringByLenght[currStringLength][i]);
}
if (uniqueStringSet.size() > 0) {
for (itr = uniqueStringSet.begin(); itr != uniqueStringSet.end(); itr++) {
for (int i = 0; i < stringByLenght[longest].size(); i++)
{
if (sContainsT(stringByLenght[longest][i], *itr)) {
length = -1;
break;
}
else
length = currStringLength;
}
}
}
currStringLength--;
}
return length;
}
// test case.
int main()
{
vector<string> strs;
int a = 0;
string strings[] = {"j","j","viez","ogk","ogk","lfn","ypmhwx","ypmhwx","m","m","ak","ivivzoncju","ivivzoncju","wmybi","wmybi","dyzfjg","dyzfjg"};
//string strings[] = { "a","b","c", "a", "b" };
//string strings[] = {"aaaaa", "aaaaa", "aaa", "aaa", "aaaaa", "aabaa"};
//string strings[] = { "aaa", "aaa", "aa"};
for (int i = 0; i < 17; i++) {
strs.push_back(strings[i]);
}
a = findLUSlength(strs);
cout << a << endl;
return 0;
}
3ms AC,时间还可以,主要是限定的字符串长度短,个数少。不过绝对不是一个好方法。
网友评论