比较字符串(包含以及变位词)

Two Strings Are Anagrams

Description

Write a method anagram(s,t) to decide if two strings are anagrams or not.

What is Anagram?

  • Two strings are anagram if they can be the same after change the order of characters.

Example

Given s = "abcd", t = "dcab", return true.
Given s = "ab", t = "ab", return true.
Given s = "ab", t = "ac", return false.

solution:

class Solution:
    """
    @param s: The first string
    @param b: The second string
    @return true or false
    """
    def countchar(self,ch):
        result = {}
        for item in ch:
            ikey = ord(item)
            if result.has_key(ikey):
                result[ikey] +=1
            else:
                result.setdefault(ikey,0)
        return result

    def anagram(self, s, t):
        # write your code here
        dicS = self.countchar(s)
        dicT = self.countchar(t)
        if not cmp(dicS,dicT):
             return True
        else:
            return False

Compare Strings

Description

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.

Notice

The characters of B in A are not necessary continuous or ordered.

Example

For A = "ABCD", B = "ACD", return true.

For A = "ABCD", B = "AABC", return false.

solution

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
    """
    # used a list with 26 iterm to save the number of each alphabet

    def compareStrings(self, A, B):
        # write your code here
        if B is None:
            return True
        elif A is None:
            return False

        CntA = self.countString(A)
        CntB = self.countString(B)

        for order in range(ord("Z")-ord("A") + 1):
            if CntA[order] < CntB[order]:
                return False

        return True

    def countString(self,string):
        count = []
        for item in range(ord("Z")-ord("A") + 1):
            count.append(0)
        for item in string:
            count[ord(item) - ord("A")] +=1
        return count

posted on 2016-06-04 17:48  xweel  阅读(185)  评论(0)    收藏  举报

导航