第1.5節(jié) 回文驗(yàn)證

創(chuàng)建于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的內(nèi)容
        for i in range(len(s)):
            dict_c[s[i]]=dict_c.get(s[i],0)+1  #默認(rèn)為0
            
        #檢查t串,并清空s的內(nèi)容,如果t和s互為回文,則字典元素個(gè)數(shù)互相抵消
        for i in range(len(t)):
            dict_c[t[i]]=dict_c.get(t[i],0)-1  #默認(rèn)為0
            
        for d in dict_c:
            if dict_c[d] != 0:
                return False
        
        return True
        
        

3 算法分析

這里主要利用回文的概念,t把s的所有元素都恰好用一遍,可以通過(guò)統(tǒng)計(jì)各個(gè)元素出現(xiàn)的次數(shù)來(lái)進(jìn)行判斷。如果s和t等長(zhǎng)且是回文,則所有字符出現(xiàn)的次數(shù)是相等的。
時(shí)間復(fù)雜度為O(n)
空間復(fù)雜度為O(n)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容