每天一道LeetCode-----判斷給定字串是否符合某個模式

來源:互聯網
上載者:User
Isomorphic Strings

原題連結Isomorphic Strings

給定兩個字串,判斷其中一個是否能轉換成另一個,轉換規則如下 必須是一對一 同一個字元兩次轉換必須相同,如果第一次字元’a’轉換成’b’,那麼當下次遇到’a’時,它就只能轉換成’b’ 不能有兩個字元轉換成相同字元,如果第一次’a’轉換成’b’,那麼之後其它的字元都不能再轉換成’b’

思路:

通過兩個數組記錄轉換規則,直到轉換完成

代碼如下

class Solution {public:    bool isIsomorphic(string s, string t) {        vector<int> nums(256, 0);        vector<int> count(256, 0);        for(int i = 0; i < s.size(); ++i) {            /* 之前沒有轉換過,記錄轉換規則 */            if(nums[s[i]] == 0 && count[t[i]] == 0) {                nums[s[i]] = t[i];                count[t[i]] = 1;            }            /* 當nums[s[i]] == t[i]時正確,否則返回false */            else if(nums[s[i]] != t[i]) {                return false;            }        }        return true;    }};
Word Pattern

原題連結Word Pattern

判斷一個字串中的單次是否按照給定模式排列

思路:

仍然是一對一的關係,和上面的類似

代碼如下

class Solution {public:    bool wordPattern(string pattern, string str) {        unordered_map<char, string> hash;        unordered_map<string, int> count;        std::istringstream oss(str);        std::string line;        for(auto ch : pattern) {            std::getline(oss, line, ' ');            if(hash.count(ch) == 0 && count.count(line) == 0) {                hash[ch] = line;                count[line] = 1;            }            else if(hash[ch] != line) {                return false;            }        }        return std::getline(oss, line) ? false : true;    }};

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.