classSolution {public:boolcheckInclusion(string s1,string s2) { unordered_map<char,int> table;for(auto c:s1)table[c]++;int windowStart =0, matched =0;for(int windowEnd =0; windowEnd <s2.length(); windowEnd++) {char endChar =s2[windowEnd];if(table.find(endChar) !=table.end()) {table[endChar]--;if(table[endChar] ==0) { matched++; } }if(windowEnd - windowStart +1>s1.length()) {char startChar =s2[windowStart++];if(table.find(startChar) !=table.end()) {if(table[startChar] ==0) matched--;table[startChar]++; } } // Note that this equals to table.size() // instead of s1.legnth() because there might be duplicate chars in s1if(matched ==table.size())returntrue; }returnfalse; }};
跑起來的效率不算好:
Runtime: 16 ms, faster than 47.09% of C++ online submissions for Permutation in String. Memory Usage: 9.4 MB, less than 93.75% of C++ online submissions for Permutation in String.