码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Valid Anagram

时间:2015-08-01 17:07:15      阅读:782      评论:0      收藏:0      [点我收藏+]

标签:

Valid Anagram 

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.

https://leetcode.com/problems/valid-anagram/

 

 

 


 

 

 

判断字符串t是不是由s交换顺序之后得到的。

开一个哈希表,记录出现的次数。

如果长度不同,直接返回false,这样就避免了最后还要遍历一把哈希表。

 1 /**
 2  * @param {string} s
 3  * @param {string} t
 4  * @return {boolean}
 5  */
 6 var isAnagram = function(s, t) {
 7     if(s.length !== t.length){
 8         return false;
 9     }
10     var i, dict = {};
11     for(i = 0; i < s.length; i++){
12         if(!dict[s[i]]){
13             dict[s[i]] = 1;
14         }else{
15             dict[s[i]]++;
16         }
17     }
18     for(i = 0; i < t.length; i++){
19         if(!dict[t[i]] || dict[t[i]] === 0){
20             return false;
21         }else{
22             dict[t[i]]--;
23         }
24     }
25     return true;
26 };

 

 

 
 
 

[LeetCode][JavaScript]Valid Anagram

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/4694221.html

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