1. 程式人生 > 其它 >leetcode_有效的字母異位詞

leetcode_有效的字母異位詞

一、題目

二、參考程式碼

使用兩個遍歷和一個數組,陣列大小為26,用來記錄字母出現的次數,這樣的想法很好,我當時想的時候,以為所有小寫字母數字為24,所以導致記憶體訪問錯誤。

參考程式碼如下:

class Solution {
public:
    bool isAnagram(string s, string t) {
        int record[26] = {0};
        for (int i = 0; i < s.size(); i++) {
            // 並不需要記住字元a的ASCII,只要求出一個相對數值就可以了
            record[s[i] - '
a']++; } for (int i = 0; i < t.size(); i++) { record[t[i] - 'a']--; } for (int i = 0; i < 26; i++) { if (record[i] != 0) { // record陣列如果有的元素不為零0,說明字串s和t 一定是誰多了字元或者誰少了字元。 return false; } }
// record陣列所有元素都為零0,說明字串s和t是字母異位詞 return true; } };

三、我的思路

我本來以為是要使用set或者是map,後來發現vector完全可以滿足要求,這樣看來我的想法還是太過複雜,但是功能基本都已經實現了。但是因為是使用24個大小的字元,所以導致

訪問出錯。而且查詢的時候也不用使用set,因為他們可以做對映,所以直接使用vector就好了,也不用兩個vector。

class Solution {
public:
    bool isAnagram(string s, string t) {
        unordered_set
<char> dict; int length_s = s.size(); int t_length = t.size(); //std::cout<<'very good!'<<std::endl; if(t_length != length_s){ return false; } vector<int> s_num(26, 0); vector<int> t_num(26,0); //std::cout<<'good!'<<std::endl; for(int i=0; i<length_s; i++){ if(dict.find(s[i]) == dict.end()){ //不在裡面,則讀入 dict.insert(s[i]); } s_num[s[i]-'a'] ++; } //for(int i=0; i<24;i++) // std::cout<<s_num[i]<<std::endl; for(int i=0; i<t_length; i++){ if(dict.find(t[i]) == dict.end()) return false; else t_num[t[i] - 'a'] ++; } //如果兩個陣列相等 int flag = 0; for(int i=0; i<24; i++){ if(s_num[i] == t_num[i]){ flag++; } else return false; } if (flag==24) return true; return false; } };
縱一葦之所如,臨萬頃之茫然。