LeetCode 242 Valid Anagram

來源:互聯網
上載者:User

標籤:term   class   val   problem   cti   and   hash   bsp   rmi   

Problem:

Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.

Summary:

給出字串s和t,判斷t是不是s的相同字母異序詞。

Analysis:

1. Hash表,記錄s中字母出現的次數,再判斷t中的字母是否有相同出現頻率。

 1 class Solution { 2 public: 3     bool isAnagram(string s, string t) { 4         int len1 = s.size(), len2 = t.size(), ch[26] = {0}; 5          6         for (int i = 0; i < len1; i++) { 7             int tmp = s[i] - ‘a‘; 8             ch[tmp]++; 9         }10         11         for (int i = 0; i < len2; i++) {12             int tmp = t[i] - ‘a‘;13             ch[tmp]--;14         }15         16         for (int i = 0; i < 26; i++) {17             if (ch[i]) {18                 return false;19             }20         }21         22         return true;23     }24 };

2. 分別給兩字串中字元由小到大排序,判斷排序後兩字串是否相等即可。但這個方法效率較低。

1 class Solution {2 public:3     bool isAnagram(string s, string t) {4         sort(s.begin(), s.end());5         sort(t.begin(), t.end());6         7         return s == t ? true : false;8     }9 };

 

LeetCode 242 Valid Anagram

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.