lintcode:Compare Strings 比较字符串

题目:

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

样例

给出 A = "ABCD" B = "ACD",返回 true

给出 A = "ABCD" B = "AABC", 返回 false

注意

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

解题:

用数组,或者用HashMap都可以,由于char String转换成Integer不是很熟悉,搞了好久。。。

Java程序:

public class Solution {
    /**
     * @param A : A string includes Upper Case letters
     * @param B : A string includes Upper Case letter
     * @return :  if string A contains all of the characters in B return true else return false
     */
    public boolean compareStrings(String A, String B) {
        // write your code here
        if(A.length()<B.length())
            return false;
        if(B==null||B.length()==0)
            return true;
        int array[] = new int[26];
        char ch;
        for(int i = 0;i< A.length();i++){
            ch = A.charAt(i);
            array[ ch - 'A' ] ++;
        }
        for(int i = 0;i< B.length();i++){
            ch = B.charAt(i);
            array[ ch - 'A' ] --;
            if(array[ ch - 'A' ] < 0)
                return false;
        }
        return true;
    }
}
View Code

总耗时: 2110 ms

通过Integer.parseInt(Str)会有异常,可以设置默认值,但是我抛出或者使用try catch 我都没有成功。。。。。下面Python利用字典实现

Python程序:

class Solution:
    """
    @param A : A string includes Upper Case letters
    @param B : A string includes Upper Case letters
    @return :  if string A contains all of the characters in B return True else return False
    """
    def compareStrings(self, A, B):
        # write your code here
        if len(A)<len(B):
            return False
        if len(B)==0 or B==None:
            return True
        d = {}
        for ai in A:
            if ai not in d:
                d[ai] = 1
            else:
                d[ai] += 1
        for bi in B:
            if bi not in d:
                return False
            else:
                d[bi] -=1
                if d[bi] < 0:
                    return False
        return True 
View Code

总耗时: 704 ms

更新

KMP算法可以尝试解题

原文地址:https://www.cnblogs.com/theskulls/p/4888269.html