日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【LeetCode】马三来刷题之Valid Anagram

發(fā)布時(shí)間:2023/12/16 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【LeetCode】马三来刷题之Valid Anagram 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

刷題第3天,題目鏈接:https://leetcode.com/problems/valid-anagram/

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.

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

兩種思路,第一種方法將數(shù)組排序以后,再比較,如果相同就返回true,否則返回false。第二種方法,建立一個(gè)map統(tǒng)計(jì)兩個(gè)字符串中每個(gè)字母出現(xiàn)的次數(shù),s中每出現(xiàn)一個(gè)字母就將對(duì)應(yīng)鍵的值++,t中每出現(xiàn)一個(gè)字母就將對(duì)應(yīng)鍵的值--。最后統(tǒng)計(jì)map中所有元素的鍵值,一旦發(fā)現(xiàn)有值不為0的就返回false,否則返回true。

方法一:

bool isAnagram(string s, string t) {sort(s.begin(),s.end());sort(t.begin(),t.end());if(s.compare(t)==0)return true;else return false; }方法二:

bool isAnagram(string s, string t) {map<char,int> m;if(s.length()!=t.length())return false;for(int i=0;i<s.length();i++){m[s[i]]++;m[t[i]]--;}for(map<char,int>::iterator it=m.begin();it!=m.end();it++){if((*it).second!=0)return false;}return true; }
在網(wǎng)上看到了一種與方法二類似的解法,只不過使用數(shù)組模擬的,更加巧妙,比map更節(jié)省空間,所以也把解法搬運(yùn)了過來:

方法三:

vector<int> count(26, 0);for(int i = 0; i < s.size(); i ++)count[s[i]-'a'] ++;for(int i = 0; i < t.size(); i ++)count[t[i]-'a'] --;for(int i = 0; i < 26; i ++)if(count[i] != 0)return false;return true;}

每天一道題,保持新鮮感,就這樣~

總結(jié)

以上是生活随笔為你收集整理的【LeetCode】马三来刷题之Valid Anagram的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。