LeetCode Valid Anagram

来源:互联网 发布:信用卡加淘宝帐号贷款 编辑:程序博客网 时间:2024/05/17 03:17

Description:

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.

Solution:

Just use two arrays, each with the length of 26, represents the length of all alphabets in lower case. Then scan each of the string, calculate the number of each alphabet in each string. If all the numbers of 26 alphabets in two strings are the same, then return true, else false.


java:

<span style="font-size:18px;">import java.util.*;public class Solution {public boolean isAnagram(String s, String t) {int counta[] = new int[26];int countb[] = new int[26];for (int i = 0; i < s.length(); i++)counta[s.charAt(i) - 'a']++;for (int i = 0; i < t.length(); i++)countb[t.charAt(i) - 'a']++;for (int i = 0; i < 26; i++)if (counta[i] != countb[i])return false;return true;}}</span>


python:

<span style="font-size:18px;">print ord("a")class Solution(object):    def isAnagram(self, s, t):        """        :type s: str        :type t: str        :rtype: bool        """        numS = []        numT = []        for i in range(26):            numS.append(i)            numT.append(i)        for i in range(len(s)):            numS[ord(s[i])-ord('a')] += 1        for i in range(len(t)):            numT[ord(t[i])-ord('a')] += 1        for i in range(26):            if(numS[i] != numT[i]):                return False                return True        </span>


或者可以调用内部方法,如下

<span style="font-size:18px;">class Solution:    def isAnagram(self, s, t):        from collections import Counter        return Counter(s).items() == Counter(t).items()</span>




0 0
原创粉丝点击