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; }

鎶€鏈浘鐗? src=

瑙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;
}

鎶€鏈浘鐗? src=

瑙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);
}

鎶€鏈浘鐗? src=

鎬荤粨

鎬讳綋鏉ヨ瑙f硶浜屾槸鏈€浼樼殑锛屼絾鍙檺浜庡綋瀛楃鍙槸灏忓啓瀛楁瘝鏃讹紝鏁扮粍鐨勮В娉曠‘瀹炴槸灞¤瘯涓嶇埥鍦╧ey纭畾鐨勬儏鍐典笅鏌ユ壘缁熻杩欑被閮藉彲浠ョ敤鏁扮粍瀹屾垚銆傚叾浠栦袱绉嶈В娉曞氨鏄€氱敤鐨勪笉闄愬埗瀛楃锛屾帓搴忕暐浼樹竴鐐广€?/p>





以上是关于LeetCode鍒濈骇绠楁硶涔嬪瓧绗︿覆锛?42 鏈夋晥鐨勫瓧姣嶅紓浣嶈瘝的主要内容,如果未能解决你的问题,请参考以下文章

銆岀畻娉曚笌鏁版嵁缁撴瀯銆嶅甫浣犵湅鍝堝笇绠楁硶涔嬬編

瀛楄妭璺冲姩鏈€甯歌€冪殑 64 閬揓S绠楁硶棰?/a>

Node.js涔嬪垽鏂瓧绗︿覆涓槸鍚﹀寘鍚煇涓瓧绗︿覆

鍥剧殑绠楁硶---寮楁礇浼婂痉绠楁硶

绠楁硶鏁版嵁缁撴瀯01 /绠楁硶鏁版嵁缁撴瀯姒傝堪