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

原文地址:https://www.cnblogs.com/whuyt/p/4814298.html