Valid Anagram 解答

本文介绍了一种使用哈希映射来判断两个字符串是否互为字谜变换的方法。通过统计每个字符出现的次数,并验证这些计数是否匹配,可以在O(n)的时间复杂度内解决问题。

Question

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.

(An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; for example Torchwood can be rearranged into Doctor Who.)

Solution

Use hashmap to count each character's appearance time. Time complexity O(n), space cost O(n).

Note here, counts.put(tmp, count.get(tmp)--); is wrong!

 

 1 public class Solution {
 2     public boolean isAnagram(String s, String t) {
 3         if (s == null || t == null)
 4             return false;
 5         if (s.length() != t.length())
 6             return false;
 7         Map<Character, Integer> counts = new HashMap<Character, Integer>();
 8         int length = s.length();
 9         for (int i = 0; i < length; i++) {
10             char tmp = s.charAt(i);
11             if (counts.containsKey(tmp)) {
12                 int count = (int)counts.get(tmp);
13                 counts.put(tmp, count + 1);
14             } else {
15                 counts.put(tmp, 1);
16             }
17         }
18         for (int i = 0; i < length; i++) {
19             char tmp = t.charAt(i);
20             if (counts.containsKey(tmp)) {
21                 int count = (int)counts.get(tmp);
22                 if (count <= 0)
23                     return false;
24                 else
25                     counts.put(tmp, count - 1);
26             } else {
27                 return false;
28             }
29         }
30         return true;
31     }
32 }

++x is called preincrement while x++ is called postincrement.

1 int x = 5, y = 5;
2 
3 System.out.println(++x); // outputs 6
4 System.out.println(x); // outputs 6
5 
6 System.out.println(y++); // outputs 5
7 System.out.println(y); // outputs 6

 

转载于:https://www.cnblogs.com/ireneyanglan/p/4809024.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值