4-21刷题

Two Strings Are Anagrams

判断两个字符串是否为重组的,没想到太好的方法,直接用计数法简单粗暴。

public class Solution {
    /**
     * @param s: The first string
     * @param b: The second string
     * @return true or false
     */
    public boolean anagram(String s, String t) {
        // write your code here
        int[] num = new int[270];
        char[] s1 = s.toCharArray();
        char[] t1 = t.toCharArray();
        if (s.length() != t.length()) return false;
        for (int i = 0; i < s.length(); ++i) {
            num[s1[i]]++;
            --num[t1[i]];
        }
        for (int i = 0; i < num.length; ++i) {
            if (num[i] != 0) return false;   
        }
        return true;
    }
};

 标准答案:

public class Solution {
    /**
     * @param s: The first string
     * @param b: The second string
     * @return true or false
     */
    public boolean anagram(String s, String t) {
        if (s.length() != t.length()) {
           return false;
        }
        
        int[] count = new int[256];
        for (int i = 0; i < s.length(); i++) {
            count[(int) s.charAt(i)]++;
        }
        for (int i = 0; i < t.length(); i++) {
            count[(int) t.charAt(i)]--;
            if (count[(int) t.charAt(i)] < 0) {
                return false;
            }
        }
        return true;
    }
};

Compare Strings

public class Solution {
    /**
     * @param A : A string includes Upper Case letters
     * @param B : A string includes Upper Case letter
     * @return :  if string A contains all of the characters in B return true else return false
     */
    public boolean compareStrings(String A, String B) {
        // write your code here
        int[] num = new int[256];
        for (int i = 0; i < A.length(); ++i) {
            ++num[(int) A.charAt(i)];
        }
        for (int i = 0; i < B.length(); ++i) {
            --num[(int)B.charAt(i)];
            if (num[(int)B.charAt(i)] < 0) return false;
        }
        return true;
    }
}
原文地址:https://www.cnblogs.com/fripside/p/4444957.html