比较两个字符串A和B,确定A中是否包含B中所有的字符。

来源:互联网 发布:自学 java c python 编辑:程序博客网 时间:2024/03/29 17:33

看到 http://blog.csdn.net/ivanmerlin/article/details/48315349 后,我用另一种方法实现。

题目样例:

给出 A = “ABCD” B = “ACD”,返回 true
给出 A = “ABCD” B = “AABC”, 返回 false

注意
在 A 中出现的 B 字符串里的字符不需要连续或者有序。

另外的一种写法如下。不对的地方还望指正。

public boolean compare(String a, String b) {        if (TextUtils.isEmpty(b)) return true;        if (TextUtils.isEmpty(a)) return false;        char[] aChars = a.toCharArray();        char[] bChars = b.toCharArray();        List<Character> aList = new ArrayList<>();        for (char aChar : aChars) {            aList.add(aChar);        }        List<Character> bList = new ArrayList<>();        for (char bChar : bChars) {            bList.add(bChar);        }        int index;        for (int i = bList.size() - 1; i >= 0; i--) {            index = aList.indexOf(bList.get(i));            if (index != -1) {                bList.remove(i);                aList.remove(index);            } else {                return false;            }        }        return true;    }
阅读全文
0 0