Here is the current fastest solution on submissions page to Leetcode 49. Group Anagrams.
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
class Solution {public:vector<vector<string>> groupAnagrams(vector<string>& strs){unordered_map<uint64_t, std::vector<std::string>> map;for (auto& word : strs)map[encode(word)].emplace_back(std::move(word));std::vector<std::vector<std::string>> result;for (auto& pair : map)result.emplace_back(std::move(pair.second));return result;}uint64_t encode(const std::string& word){uint16_t counter[26] = {0};for (char c : word) ++counter[c - 'a'];uint64_t result = 0;uint64_t degree = 1;for (int i = 0; i < 26; ++i){result += degree * (counter[i]);degree *= 26;}return result;}};
Take a look at the "encode" function, which serves as a hash map from a string to an integer. Do you see any flaws?
I explained the flaw and gave a counterexample and a patched solution here. I spotted the problem immediately when I saw it, because I thought about something similar when I was solving the problem myself, and I noticed that it didn't work unless I can find a workaround. But somehow, the solution above passed all the test cases. So, yeah, in most cases it would work correctly, but with a certain probability it would fail, and it's guaranteed to fail when it's analyzed and targeted.The solution in question isDescription
You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner.
Write a function to determine if the starting player can guarantee a win.
class Solution {public:bool canWin(string &s) {int _true = 0, _false = 0;if(s.length() < 2) {return false;}else {int i = 0, t = 0;while(i < s.length()) {if(!(s[i] == '+' && s[i + 1] == '+')) {i++;}else {t++;int j = i;for(; j < s.length(); ++j) {if(s[j] != '+') {break;}}int len = j - i;i = j;bool tmp = true;if(len != 3 && (len % 2)) {tmp = false;}if(tmp) {_true++;}else {_false++;}}}}if(_true == 2) {return false;}else if(_true > 0 || _false > 1) {return true;}else {return false;}}};