每日說(shuō)一點(diǎn):終于談妥
壓抑了很久的工作定位于今凌晨1點(diǎn)終于在電話溝通中初步解決。很多事的成與不成與溝通關(guān)聯(lián)甚重侄泽。日常我是個(gè)心里有事暫時(shí)藏起來(lái)的人礁芦,但藏不住事也滅不了心里的想法。找了很多朋友談人生談人性,不知是我矯情,或是世道如是?
但終歸來(lái)說(shuō),我應(yīng)該去爭(zhēng)取我的意愿姑躲,做自己更愿意和熱情的事。與我目前助益微薄的瑣碎,我想放放。
凌亂了24小時(shí),又開(kāi)始了心安的自由的生活活翩。
信仰烹骨、閱讀、刷題材泄、英語(yǔ)沮焕、日語(yǔ)、產(chǎn)品拉宗,This is my life.
合法異序字符串
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?
判斷兩個(gè)字符串峦树,是異序相等的。
解法一:排序
我的第一想法就是排序旦事,既然異序魁巩,就將兩個(gè)字符串排序后,如果一致就是相等的姐浮。
上我的代碼:
class Solution {
public:
int cnt[26]; //全局變量int數(shù)組的初始值才是0谷遂;
bool isAnagram(string s, string t) {
//解法二,計(jì)數(shù)表卖鲤,排序復(fù)雜度nlogn肾扰,計(jì)數(shù)表是n。
for(int i = 0; i < s.length(); i++){
cnt[s[i] - 'a'] ++;
}
for(int i = 0; i < t.length(); i++){ //一樣的字母會(huì)減去積累
cnt[t[i] - 'a'] --;
}
for(int i = 0; i < 26; i++){
if( cnt[i] ) //如果cnt計(jì)數(shù)有非零
return false;
}
return true;
}
};
排序時(shí)間復(fù)雜度是nlogn蛋逾,相比較于解法二的n集晚,確實(shí)笨了。80ms区匣。
解法二:哈希表計(jì)數(shù)
基于字符數(shù)是有限的偷拔,就用int數(shù)組記下對(duì)應(yīng)角標(biāo)字符的數(shù)量。第一個(gè)字符串用++,第二個(gè)用--条摸,最終都回歸到0平衡時(shí)悦污,說(shuō)明數(shù)目都一樣。
貼我學(xué)習(xí)解法二后自己的代碼:
class Solution {
public:
int cnt[26]; //全局變量int數(shù)組的初始值才是0钉蒲;
bool isAnagram(string s, string t) {
//解法二切端,計(jì)數(shù)表,排序復(fù)雜度nlogn顷啼,計(jì)數(shù)表是n踏枣。
for(int i = 0; i < s.length(); i++){
cnt[s[i] - 'a'] ++;
}
for(int i = 0; i < t.length(); i++){ //一樣的字母會(huì)減去積累
cnt[t[i] - 'a'] --;
}
for(int i = 0; i < 26; i++){
if( cnt[i] ) //如果cnt計(jì)數(shù)有非零
return false;
}
return true;
}
};
復(fù)雜度就是n,12ms钙蒙。此法更快一點(diǎn)茵瀑。
如果適配Unicode字符?
我想就是不僅限于26個(gè)字母躬厌,但好在每個(gè)Unicode的字符都是有角標(biāo)的马昨,擴(kuò)大int數(shù)組的容量就好了吧~
周五回家并參加婚禮。我想我該好好陪家人并珍惜時(shí)光扛施。
——End——