LeetCode鍒濈骇绠楁硶涔嬪瓧绗︿覆锛?42 鏈夋晥鐨勫瓧姣嶅紓浣嶈瘝
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode鍒濈骇绠楁硶涔嬪瓧绗︿覆锛?42 鏈夋晥鐨勫瓧姣嶅紓浣嶈瘝相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/%e8%bf%9b%e9%98%b6' title='杩涢樁'>杩涢樁
http 闄愬埗 杩斿洖 size 鐩哥瓑 isa git array鏈夋晥鐨勫瓧姣嶅紓浣嶈瘝
棰樼洰鍦板潃锛?a href="https://leetcode-cn.com/problems/valid-anagram/" target="_blank">https://leetcode-cn.com/problems/valid-anagram/
缁欏畾涓や釜瀛楃涓?s 鍜?t 锛岀紪鍐欎竴涓嚱鏁版潵鍒ゆ柇 t 鏄惁鏄?s 鐨勫瓧姣嶅紓浣嶈瘝銆?/p>
绀轰緥 1:
杈撳叆: s = "anagram", t = "nagaram"
杈撳嚭: true
绀轰緥 2:
杈撳叆: s = "rat", t = "car"
杈撳嚭: false
璇存槑:
浣犲彲浠ュ亣璁惧瓧绗︿覆鍙寘鍚皬鍐欏瓧姣嶃€?/p>
杩涢樁:
濡傛灉杈撳叆瀛楃涓插寘鍚?unicode 瀛楃鎬庝箞鍔烇紵浣犺兘鍚﹁皟鏁翠綘鐨勮В娉曟潵搴斿杩欑鎯呭喌锛?/p>
public boolean isAnagram(String s, String t) { char[] ss = s.toCharArray(); char[] tt = t.toCharArray(); //闀垮害閮戒笉涓€鏍风洿鎺ヨ蛋寮€ if (ss.length != tt.length) { return false; } Map<Character, Integer> map = new HashMap<Character, Integer>(); for (int i = 0; i < ss.length; i++) { char c1 = ss[i]; char c2 = tt[i]; //缁熻濡傛灉鏄湡鐨勬槸寮備綅璇嶆渶鍚巏ey鍊间负0 map.put(c1, map.getOrDefault(c1, 0) + 1); map.put(c2, map.getOrDefault(c2, 0) - 1); } //閬嶅巻琛?涓嶆槸寮備綅璇嶅氨鏈夊涔熸湁灏? for (int i = 0; i < map.size(); i++) { if (map.get(tt[i]) != 0) { return false; } } return true; }
瑙f硶浜岋細鏁扮粍
鍜屼互鍓嶈В棰樹竴鏍风敤Hash琛ㄨ兘鍋氬氨瑕佽€冭檻涓€涓嬪彲涓嶅彲浠ョ敤鏁扮粍鏉ュ仛锛岀敤鏁扮粍鐨勫眬闄愭槸瀹冩槸鍥哄畾鐨勩€傛墍浠ュ鏋滆褰曠殑key鏄浐瀹氱殑涓嶅灏卞彲浠ョ敤銆傝繖閲屼篃灏辨槸26涓瓧姣?/p>
public boolean isAnagram(String s, String t) {
char[] ss = s.toCharArray();
char[] tt = t.toCharArray();
//闀垮害閮戒笉涓€鏍风洿鎺ヨ蛋寮€
if (ss.length != tt.length) {
return false;
}
int[] table = new int[26];
for (int i = 0; i < ss.length; i++) {
int c1 = ss[i] - "a";
int c2 = tt[i] - "a";
//缁熻濡傛灉鏄湡鐨勬槸寮備綅璇嶆渶鍚巏ey鍊间负0
table[c1]++;
table[c2]--;
}
//閬嶅巻琛?涓嶆槸寮備綅璇嶅氨鏈夊涔熸湁灏? for (int i = 0; i < 26; i++) {
if (table[i] != 0) {
return false;
}
}
return true;
}
瑙f硶涓夛細鎺掑簭
涓嶅氨鏄綅缃笉鍚屽槢锛屾帓涓簭涓嶅氨鏄浉绛夊瓧绗︿覆浜嗭紝灏变笉鐢ㄧ粺璁″瓧绗︿覆涓殑姣忎釜瀛楃鏁伴噺銆備笉杩囨帓搴忔渶浼樹篃鏄墠nlogn锛屾墍浠ュ苟涓嶄紭鍙槸瑙h繖棰樻瘮杈冪畝鍗曠洿鎺ワ紝鐢氳嚦鍙互鐩存帴涓€鍙ヨ繑鍥?/p>
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
char[] str1 = s.toCharArray();
char[] str2 = t.toCharArray();
Arrays.sort(str1);
Arrays.sort(str2);
return Arrays.equals(str1, str2);
}
鎬荤粨
鎬讳綋鏉ヨ瑙f硶浜屾槸鏈€浼樼殑锛屼絾鍙檺浜庡綋瀛楃鍙槸灏忓啓瀛楁瘝鏃讹紝鏁扮粍鐨勮В娉曠‘瀹炴槸灞¤瘯涓嶇埥鍦╧ey纭畾鐨勬儏鍐典笅鏌ユ壘缁熻杩欑被閮藉彲浠ョ敤鏁扮粍瀹屾垚銆傚叾浠栦袱绉嶈В娉曞氨鏄€氱敤鐨勪笉闄愬埗瀛楃锛屾帓搴忕暐浼樹竴鐐广€?/p>
以上是关于LeetCode鍒濈骇绠楁硶涔嬪瓧绗︿覆锛?42 鏈夋晥鐨勫瓧姣嶅紓浣嶈瘝的主要内容,如果未能解决你的问题,请参考以下文章