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.
java 求解:
package com.free4lab.learning.leetcode;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class Anagrams {
public static void main(String[] args) {
String t = "nagaram";
String s = "anagram";
System.out.println(new Anagrams().isAnagram(s,t));
}
public boolean isAnagram(String s, String t) {
if(s.length() != t.length())
return false;
Map<String, Integer> map = new HashMap<String, Integer>();
for(int i = 0; i < t.length(); i++) {
if(map.containsKey(t.charAt(i) + "")) {
map.put(t.charAt(i) + "", map.get(t.charAt(i) + "")+1);
} else {
map.put(t.charAt(i) + "", 1);
}
}
for(int i = 0; i < s.length(); i++) {
if(map.containsKey(s.charAt(i) + "")) {
map.put(s.charAt(i) + "", map.get(s.charAt(i) + "") - 1);
//System.out.println("in this.");
} else {
//System.out.println("not in this.");
}
}
boolean flag = true;
for(Entry<String, Integer> entry : map.entrySet()) {
if(entry.getValue() != 0)
flag = false;
//System.out.println(entry.getKey() + " : " + entry.getValue());
}
//System.out.println( s.charAt(0) + "");
return flag;
}
}
因为不熟悉 C++,涉及到字符串,当时第一想到的是哈希表,所以用了java。
但是后来想想也可以不用哈希,而是自己实现相应的逻辑就好了,说白了还是偷懒了,虽然上述代码效率不高,但是思路非常简单。
回头重新优化一下。
两篇好文,关于回文数的题目:
http://blog.csdn.net/linhuanmars/article/details/21664747
http://algorithm.yuanbin.me/string/two_strings_are_anagrams.html