天天看點

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

初步思路:

如果兩個字元串長度不等,直接傳回 false

如果是 ascii 碼,建立一個字母表大小的 int數組, 周遊一次字元串将相應數組元素值+1,然後在周遊另一個字元串,将相應數組元素值-1, 如果值已經為0,傳回 false。

時間複雜度: O(n)

空間複雜度: O(1)

public class solution {
    
    public boolean solu(String s1, String s2) {
        if (s1.length() != s2.length())
            return false;
        int index, ascii[] = new int[256];
        for (int i = 0; i < s1.length(); i++) {
            index = s1.charAt(i);
            ascii[index]++;
        }
        for (int j = 0; j < s2.length(); j++) {
            index = s2.charAt(j);
            if (ascii[index] == 0)
                return false;
            ascii[index]--;
        }
        return true;
    }
}      

2015-09-16