1. 程式人生 > >LintCode Two Strings Are Anagrams 兩個字串是變位詞

LintCode Two Strings Are Anagrams 兩個字串是變位詞

寫出一個函式 anagram(s, t) 去判斷兩個字串是否是顛倒字母順序構成的。
樣例
給出 s=”abcd”,t=”dcab”,返回 true。

Write a method anagram(s,t) to decide if two strings are anagrams or not.
Example
Given s=”abcd”, t=”dcab”, return true.

Challenge
O(n) time, O(1) extra space

public class Solution {
    /**
     * @param s: The first string
     * @param
b: The second string * @return true or false */
public boolean anagram(String s, String t) { if(s.length() != t.length()) return false; Map<Character, Integer> map = new HashMap<Character, Integer>(); for(int i = 0; i < s.length(); i++) { char
c = s.charAt(i); if(map.containsKey(c)) { map.put(c, map.get(c) + 1); }else { map.put(c, 1); } c = t.charAt(i); if(map.containsKey(c)) { map.put(c, map.get(c) - 1); }else { map.put(c, -1
); } } for(char key : map.keySet()) { int value = map.get(key); if(value != 0) return false; } return true; } }