158. Valid Anagram

題目

https://www.lintcode.com/problem/valid-anagram/description?_from=ladder&&fromId=2

實現

  1. 創建兩個長度爲 256 的 list
  2. 統計兩個字符串中字符的出現的次數
  3. 如果統計是一樣的,那麼說明是 Anagram

代碼

class Solution:
    """
    @param s: The first string
    @param t: The second string
    @return: true or false
    """
    def anagram(self, s, t):
        if s is None or t is None:
            return False
            
        s_chars = [0] * 256
        t_chars = [0] * 256
        
        for char in s:
            s_chars[ord(char)] += 1
        
        for char in t:
            t_chars[ord(char)] += 1
            
        for i in range(256):
            if s_chars[i] != t_chars[i]:
                return False
        
        return True
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章