Compare strings

Compare two strings A and B, determine whether A contains all of the characters in B.The characters in string A and B are all Upper Case letters.

Example:
For A = "ABCD", B = "ABC", return true.
For A = "ABCD" B = "AABC", return false.

分析:
String 里的字符不是有序的,出现的次数也不一。若B 中的某一字符出现次数多于 A,则为 false。
因此,问题的关键在于,统计 B 中不同字符出现的次数,一旦发现此字符在 A 中对应的出现次数比 B 小,那么即可返回 false。

自己写的啰嗦版:

 public boolean compareStrings(String A, String B) {
        int[] AA = new int[26];
        int[] BB = new int[26];
        for (int i=0; i<A.length(); i++) {
            AA[A.charAt(i) - 'A']++;
        }

        for (int i=0; i<B.length(); i++) {
            BB[B.charAt(i) - 'A']++;
        }

        for(int i =0; i<26; i++) {
            if (BB[i]>AA[i]) 
                return false;
        }
        return true;
    }

网上找的简洁版:
chu'chu

public boolean compareStrings(String A, String B) {
        // write your code here
        int[] AA = new int[26];
        int[] BB = new int[26];
        for (int i=0; i<A.length(); i++) {
            AA[A.charAt(i) - 'A']++;
        }
        
        for (int i=0; i<B.length(); i++) {
            BB[B.charAt(i) - 'A']++;

            //每次++后就和 AA 比较,如果出现大于 AA 的情况,返回 false
            if (BB[B.charAt(i) - 'A'] > AA[B.charAt(i) - 'A']) return false;
        }
        
        return true;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容