Commit 92e9d7ee authored by yaozc's avatar yaozc
Browse files

keep going

parent d423a8df
......@@ -158,6 +158,98 @@ public:
};
// Group Anagrams
// 用c++的map (二叉树)作为data structure
// 每个单词sort后的string作为key
// 注意!!!每个单词的char单独相加,值作为value,key为值相同的单词(vector)的方法不work!!
// 因为1+2+3 = 2 + 2 + 2且几乎无法区分!
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> result;
map<string, std::vector<string>> table;
for (int i = 0; i < strs.size(); i++) {
string the_key = strs[i];
sort(the_key.begin(),the_key.end());
table[the_key].push_back(strs[i]);
}
for (auto it = table.begin(); it != table.end(); it++) {
result.push_back(it->second);
}
return result;
}
};
// First Unique Character in a String
// using a vector that has the space of 26 and increament each char for every matching space is a good idea!!
// it's much better than have a map
class Solution {
public:
int firstUniqChar(string s) {
vector<int> count(26, 0);
for(int i=0; i<s.size(); i++){
count[s[i]-'a']++;
}
for(int i=0; i<s.size(); i++){
if(count[s[i]-'a'] == 1){
return i;
}
}
return -1;
}
};
// Valid Parentheses
// solution looks ugly but work, no really better solutions
class Solution {
public:
bool isValid(string s) {
stack<char> mystack;
mystack.push('1');
for(int i=0; i<s.size(); i++){
if(s[i] == ']'){
if(mystack.top() == '['){
mystack.pop();
}
else{
return false;
}
}
else if(s[i] == '}'){
if(mystack.top() == '{'){
mystack.pop();
}
else{
return false;
}
}
else if(s[i] == ')'){
if(mystack.top() == '('){
mystack.pop();
}
else{
return false;
}
}
else{
mystack.push(s[i]);
}
}
return mystack.top() == '1' ? true : false;
}
};
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment