You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求更简洁的字符串字母模式匹配函数实现方案

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:

  • AABB vs CCDD: Both generate "0011" → returns true
  • ABAB vs CDCD: Both generate "0101" → returns true
  • AAFFG vs AAFGF: Patterns are "00112" vs "00121" → returns false
  • asdasd vs qweqwe: Patterns are "012012" vs "012012" → returns true

All cases work as expected!

内容的提问来源于stack exchange,提问作者BooRuleDie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:33:33