LintCode题解之比较字符串


 

使用标记的方式,先遍历一遍B,出现一次就记录一次出现次数,然后遍历A,将记录的B的出现次数消去,最后检查一下记录的标记位是不是都消去了,总共需要检查三次,即进行三次O(n)的遍历。

然后总结出规律如果A的字符长度小于B的字符长度时,A不可能完全包含B,所以做一个优化处理,先检查一下长度,如果能够确定结果的话就直接返回了。

AC代码:

public class Solution {
    
    /*
     * @param A: A string
     * @param B: A string
     * @return: if string A contains all of the characters in B return true else return false
     */
    public boolean compareStrings(String A, String B) {
        
        if(A.length()<B.length()) return false;
        
        int[] book = new int[26];
        for(int i=0; i<B.length(); i++){
            book[B.charAt(i)-'A']++;
        }
        for(int i=0; i<A.length(); i++){
            book[A.charAt(i)-'A']--;
        }
        for(int i=0; i<book.length; i++){
            if(book[i]>0) return false;
        }
        return true;
    }
    
}

  

题目来源: http://www.lintcode.com/zh-cn/problem/compare-strings/

原文地址:https://www.cnblogs.com/cc11001100/p/7898176.html