• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

还不知道Unicode 该怎么做

只有lowercase alphabets的做法无外乎sort, hashmap, array, bitmap之类的

 Better:

1 public class Solution {
2     public boolean isAnagram(String s, String t) {
3         int[] alphabet = new int[26];
4         for (int i = 0; i < s.length(); i++) alphabet[s.charAt(i) - 'a']++;
5         for (int i = 0; i < t.length(); i++) alphabet[t.charAt(i) - 'a']--;
6         for (int i : alphabet) if (i != 0) return false;
7         return true;
8     }
9 }

 Unicode Follow up

In Java, a Unicode could be represented by a single char(BMP, Basic Multilingual Plane) or two chars (high surrogate). Bascially, we can use

 

  • String.codePointAt(int index) method to get the integer representation of a Unicode (as the key in the hash table)
  • and use Character.charCount(int code) to count how many the characters are used there (to correctly increase our index)
 1 public class Solution {
 2     public boolean isAnagram(String s, String t) {
 3         if (s==null && t==null) return true;
 4         else if (s==null || t==null) return false;
 5         else if (s.length() != t.length()) return false;
 6         
 7         Map<Integer, Integer> dict = new HashMap<>();
 8         int index = 0;
 9         while(index < s.length()) {
10             int charCode = s.codePointAt(index); // Get the integer representation of Unicode 
11             dict.put(charCode, dict.getOrDefault(charCode, 0) + 1);
12             index += Character.charCount(charCode); // The Unicode could be represented by either one char or two chars
13         }
14         
15         index = 0;
16         while(index < t.length()) {
17             int charCode = t.codePointAt(index);
18             int count = dict.getOrDefault(charCode, 0);
19             
20             if (count == 0) return false;
21             else dict.put(charCode, count - 1);
22             
23             index += Character.charCount(charCode);
24         }
25         
26         return true;
27     }
28 }

 

posted @ 2015-12-20 13:24  neverlandly  阅读(331)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3