Cracking the coding interview--Q1.3

原文java

Given two strings, write a method to decide if one is a permutation of the other.數組

譯文ide

給你兩個字符串,寫一個方法來判斷其中一個是否是另外一個的permutation。若是兩個字符串含有相同的字符,僅僅是順序可能不一樣,那麼他們就叫permutations。例如"ABCDEF"和"FEDCBA",咱們能夠認爲它們是permutation。spa

解答code

若是長度不一樣,則必定不是,不然咱們能夠先將兩個字符串內的字符按字典序排序,而後再判斷是否相等。blog

import java.util.Arrays;

public class Main {

    public static boolean isPermutation (String s1, String s2) {
        if(s1.length() != s2.length())
            return false;
        if(s1.equals(s2))
            return true;
        char a[] = s1.toCharArray();
        char b[] = s2.toCharArray();
        Arrays.sort(a);
        Arrays.sort(b);
        return Arrays.toString(a).equals(Arrays.toString(b));
    }
        
    public static void main(String args[]) {
        String s1 = "ABCDEF";
        String s2 = "FEDCBA";
        String s3 = "ABCDEE";
        System.out.println(isPermutation(s1,s2));
        System.out.println(isPermutation(s1,s3));
    }
}

O(n)的解法排序

因爲組成變位詞的字符是如出一轍的, 所以咱們能夠先統計每一個字符串中各個字符出現的次數, 而後看這兩個字符串中各字符出現次數是否同樣。若是是,則它們是一對變位詞。 這須要開一個輔助數組來保存各字符的出現次數。咱們能夠開一個大小是256的整數數組, 遍歷第一個字符串時,將相應字符出現的次數加1;遍歷第二個字符串時, 將相應字符出現的次數減1。最後若是數組中256個數都爲0,說明兩個字符串是一對變位詞。 (第1個字符串中出現的字符都被第2個字符串出現的字符抵消了), 若是數組中有一個不爲0,說明它們不是一對變位詞。ci

public static boolean isPermutation2 (String s1, String s2) {
        int len = s1.length();
        if(len != s2.length())
            return false;
        if(s1.equals(s2))
            return true;
        int [] count = new int[256];
        for(int i = 0; i < 256; i++) {
            count[i] = 0;
        }
        for(int i = 0; i < len; i++) {
            count[s1.charAt(i)]++;
            count[s2.charAt(i)]--;
        }
        for(int i = 0; i < 256; i++) {
            if(count[i] != 0)
                return false;
        }
        return true;
    }
相關文章
相關標籤/搜索