码迷,mamicode.com
首页 > 其他好文 > 详细

242_Valid Anagram

时间:2015-12-25 18:42:15      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

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?

 

 

判断是否是回文,即判断是否两个数组只是顺序不同,内容一致。

记录第一个数组中每个字母出现次数,遍历第二个数组,遇到一个就减去一次该字母出现次数

遍历出现次数的数组,全部为0则说明两个数组一样

 

public class Solution {
    public bool IsAnagram(string s, string t) {
        if(s.Length != t.Length)
        {
            return false;
        }
        
        int[] count = new int[26];
        char[] sList = s.ToCharArray();
        char[] tList = t.ToCharArray();
        
        for(int i = 0; i < s.Length; i++)
        {
            count[(int)sList[i] - (int)a]++;
        }
        
        for(int i = 0;i < t.Length; i++)
        {
            count[(int)tList[i] - (int)a]--;
        }
        
        for(int i = 0; i < count.Count(); i++)
        {
            if(count[i] != 0)
            {
                return false;
            }
        }
        
        return true;
    }
}

 

242_Valid Anagram

标签:

原文地址:http://www.cnblogs.com/Anthony-Wang/p/5076353.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!