求更简洁的字符串字母模式匹配函数实现方案
Simplifying Letter Pattern Matching in C++
Hey there! Your current implementation gets the job done, but we can make it much cleaner, more efficient, and easier to read. Let's break down how to streamline this.
The Core Idea
Instead of modifying the original strings directly with nested loops, we can convert each string into a pattern sequence—a representation where each unique character is replaced by the order it first appears. For example:
- "AABB" becomes "0011"
- "CCDD" becomes "0011"
- "ABAB" becomes "0101"
- "CDCD" becomes "0101"
If both strings generate the same pattern sequence, they have the same letter pattern.
Simplified Implementation
Here's a streamlined version using unordered_map to track character-to-pattern mappings:
#include <iostream> #include <string> #include <unordered_map> using namespace std; // Helper function to convert a string to its pattern sequence string getPattern(const string& s) { unordered_map<char, int> charMap; string pattern; int index = 0; for (char c : s) { if (charMap.find(c) == charMap.end()) { charMap[c] = index++; } // Append the mapped index as a string segment pattern += to_string(charMap[c]); } return pattern; } bool LetterPattern(const string& str1, const string& str2) { // Early exit if lengths don't match if (str1.length() != str2.length()) { return false; } // Compare the generated patterns directly return getPattern(str1) == getPattern(str2); } int main() { cout << "Please enter two string variables: "; string str1, str2; cin >> str1 >> str2; cout << "Same Letter Pattern: " << boolalpha << LetterPattern(str1, str2) << endl; return 0; }
Why This Is Better
- Efficiency: This runs in O(n) time (where n is the length of the strings) instead of your original O(n²) nested loops—way faster for longer strings.
- Readability: The logic is straightforward: convert each string to its pattern, then compare. No extra counter checks or messy direct string modification needed.
- Less Redundancy: The helper function avoids repeating code for both strings, and we don't need a special case for all-unique characters (the pattern generation handles that automatically).
Testing Your Examples
Let's verify with your test cases:
AABBvsCCDD: Both generate "0011" → returnstrueABABvsCDCD: Both generate "0101" → returnstrueAAFFGvsAAFGF: Patterns are "00112" vs "00121" → returnsfalseasdasdvsqweqwe: Patterns are "012012" vs "012012" → returnstrue
All cases work as expected!
内容的提问来源于stack exchange,提问作者BooRuleDie
相关产品推荐
相关产品推荐

