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.
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
- Leetcode #242 Valid Anagram
- leetcode-242-Valid Anagram
- Leetcode: Valid Anagram
- 【leetCode】Valid Anagram
- [leetcode] 242.Valid Anagram
- leetcode 242: Valid Anagram
- 【leetcode】Valid Anagram
- [leetcode] Valid Anagram
- LeetCode Valid Anagram
- 【LeetCode】242 Valid Anagram
- [LeetCode] Valid Anagram
- leetcode: Valid Anagram
- leetCode(53):Valid Anagram
- leetcode Valid Anagram 异位体
- [leetcode 242]Valid Anagram
- leetcode Valid Anagram
- leetCode #242 Valid Anagram
- LeetCode题解:Valid Anagram
- pig优化器之一(翻译pig wiki):combiner使用
- SPOJ 题目 8222 NSUBSTR - Substrings(后缀自动机+DP求子串出现最大次数)
- hdu1572
- HDU 5113 Black And White(2014ACM/ICPC北京赛区B)
- hdu1016
- LeetCode Valid Anagram
- hdu1015
- hdu1716
- LeetCode Sort List
- 【Leetcode】Construct binary tree from inorder and postorder traversal
- Java Difference between Private and Protected
- babyos (一)——利用BIOS 中断INT 0x10显示字符和字符串
- 高效程序的秘密_hacker's delight读书笔记
- LeetCode Convert Sorted List to Binary Search Tree