zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    怎样用 koa-router 实现 get 请求
    怎样用 koa-bodyparser 获取 POST 请求上下文中的表单数据
    怎样用 Koa 搭配 fs 模块返回一个 html 文件给前端
    怎样用 koa 解析出 POST 请求上下文中的表单数据
    怎样用 Koa 写 Hello, World!
    怎样使用 Vue-CLI 创建 Vue3 项目
    Koa 中怎样获取请求中的 query 参数
    怎样开发一个最简版 Koa 日志打印中间件
    怎样安装 Koa
    辅助理解 this 的一些代码片段
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5060721.html
Copyright © 2011-2022 走看看