• 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 }
  • 相关阅读:
    web自动化中的上传操作
    HTTP协议
    创建一个get测试
    下载安装
    unittest 介绍
    selenium常用操作
    video视频操作
    调用JavaScript
    下拉框操作
    弹窗操作
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5060721.html
Copyright © 2020-2023  润新知