第1.5節 回文驗證

創建于20170308
原文鏈接:https://leetcode.com/problems/valid-anagram/?tab=Description

1 題目

Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

2 題解:python

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False
        
        dict_c={}
        #檢查s串,并登記s的內容
        for i in range(len(s)):
            dict_c[s[i]]=dict_c.get(s[i],0)+1  #默認為0
            
        #檢查t串,并清空s的內容,如果t和s互為回文,則字典元素個數互相抵消
        for i in range(len(t)):
            dict_c[t[i]]=dict_c.get(t[i],0)-1  #默認為0
            
        for d in dict_c:
            if dict_c[d] != 0:
                return False
        
        return True
        
        

3 算法分析

這里主要利用回文的概念,t把s的所有元素都恰好用一遍,可以通過統計各個元素出現的次數來進行判斷。如果s和t等長且是回文,則所有字符出現的次數是相等的。
時間復雜度為O(n)
空間復雜度為O(n)

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容