algorithm-anagrams js关于“回文”的小算法
javascript是非常容易调试的,经常练习一些小算法,以免脑子呆木。
一个JS的算法题
Please use javascript (or your favorite programming language) to write a
function that do the following.
Given an array of strings, return an array of arrays of strings that
groups all anagrams.
An anagram is a word that has the same letters, but in different positions.
i.e. given [“cars”, “thing”, “scar”, “dog”, “god”, “arcs”, “the”]
return [[“cars”, “scar”, “arcs”], [“thing”], [“dog”, “god”], [“the”]]
This is my answer:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27function foo(arr) {
	var len=arr.length;
	var result=new Array();
	var n=0;
	for(var i=0; i<len; i++) {
		var word=arr[i];
		if(''==word) continue;
		result[n] = new Array(word);
		for(var j=i+1; j<len; j++) {
			if(true==tool(word, arr[j])) {
				result[n].push(arr[j]);
				arr[j]='';
			}
		}
		n++;
	}
	return result;
}
var testStr = ["cars", "thing", "scar", "dog", "god", "arcs", "the"];
console.log(foo(testStr));
function tool(item, str) {
	if(item.length==str.length) {
		return item.split("").sort().join("")==str.split("").sort().join("");
	}
	return false;
}