首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

LeetCode 290 Word Pattern:istringstream 分割 + 雙向映射驗證

     編輯:關於C++

題目重述

判斷字串 str(單詞以空格分隔)是否符合模式 pattern(字母)。需建立字母與單詞的**雙向一一對應**。

解題策略:編碼序列比較

將 pattern 和 str 分別轉為「首次出現索引序列」,比較兩序列是否相同。

  • abba → 0,1,1,0
  • dog cat cat dog → 0,1,1,0
  • 序列相同 ⇔ 模式匹配。

關鍵技術:istringstream 分割字串

vector split(const string& s) {
    istringstream iss(s);
    string word;
    vector res;
    while (iss >> word) res.push_back(word); // 自動按空白分割
    return res;
}

完整代碼

class Solution {
    vector encodePattern(const string& pat) {
        unordered_map mp;
        vector seq;
        int idx = 0;
        for (char c : pat) {
            if (!mp.count(c)) mp[c] = idx++;
            seq.push_back(mp[c]);
        }
        return seq;
    }
    
    vector encodeWords(const string& str) {
        istringstream iss(str);
        string word;
        unordered_map mp;
        vector seq;
        int idx = 0;
        while (iss >> word) {
            if (!mp.count(word)) mp[word] = idx++;
            seq.push_back(mp[word]);
        }
        return seq;
    }
    
public:
    bool wordPattern(string pattern, string str) {
        vector p = encodePattern(pattern);
        vector s = encodeWords(str);
        return p == s; // 長度不同自動 false
    }
};

複雜度

  • 時間:O(n),n 為字串總長度。
  • 空間:O(m),m 為不同字母/單詞數。

優點

  1. 統一編碼邏輯,代碼簡潔復用。
  2. istringstream 自動處理多空格、前後空格等邊界情況。
  3. 向量直接比較 ==,可讀性極高。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved