现有两个仅由小写英文字母构成的字符串,请判断它们是否为字母异位词,如果是的话,输出字母异位词的长度,不是的话,返回-1
注:如果每个字符出现的次数都相同,则称他们为字母异位词。
数据范围:
"aba","aa"
-1
第一个字符串与第二个字符串a出现的次数相同,而b出现的次数不同,不符合每个字符出现的次数都相同。故输出-1
"a","a"
1
第一个字符串与第二个字符串每个字符出现的次数都相同,故输出相同的长度为1
package main //import "fmt" /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @param c string字符串 * @return int整型 */ func isCongruent( s string , c string ) int { if len(s)!=len(c){ return -1 } cnt:=map[byte]int{} for _,ch:=range []byte(s){ cnt[ch]++ } for _,ch:=range []byte(c){ if _,ok:=cnt[ch];!ok{ return -1 }else{ if cnt[ch]==1{ delete(cnt,ch) }else{ cnt[ch]-- } } } if len(cnt)==0{ return len(s) } return -1 }
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @param c string字符串 * @return int整型 */ int isCongruent(char* s, char* c ) { // write code here if(strlen(s)!=strlen(c)) return -1; int *hash1=(int *)calloc(26,sizeof(int)); int *hash2=(int *)calloc(26,sizeof(int)); for(int i=0;i<strlen(s);i++){ hash1[s[i]-'a']+=1; hash2[c[i]-'a']+=1; } int count=0; for(int j=0;j<26;j++){ if(hash1[j]!=hash2[j]) return -1; if(hash1[j]!=0) count+=1; } return strlen(s); }
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @param c string字符串 * @return int整型 */ int isCongruent(string s, string c) { // write code here if(s.length()!=c.length()) return -1; vector<int> arr(26,0); for(auto &ch:s) { arr[ch-'a']++; } for(auto &ch:c) { arr[ch-'a']--; if(arr[ch-'a']<0) return -1; } return s.length(); } };