zoukankan      html  css  js  c++  java
  • 242. Valid Anagram

    Given two strings s and , write a function to determine if t is an anagram of s.

    Example 1:

    Input: s = "anagram", t = "nagaram"
    Output: true
    

    Example 2:

    Input: s = "rat", t = "car"
    Output: 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, c - 'a'可能会变成负数,因为减a是为了让小写字母map到从0到25的index上,unicode可以用hashmap来记录

    //Time: O(n), Space: O(n)
        public boolean isAnagram(String s, String t) {
            if (s.length() != t.length()) {//一定不要忘记开始先比较长度,eg:"ab", "a"
                return false;
            }
            
            int[] map = new int[26];
            
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                map[c - 'a']++;
            }
            
            for (int i = 0; i < t.length(); i++) {
                char c = t.charAt(i);
                map[c - 'a']--;
                
                if (map[c - 'a'] < 0) {
                    return false;
                }
            }
            
            return true;
        }
  • 相关阅读:
    备忘
    基于ZooKeeper实现分布式锁
    git 使用ssh密钥
    git 的安装及使用
    sqlalchemy 使用pymysql连接mysql 1366错误
    SQL语句及5.7.2 mysql 用户管理
    C 实现快速排序
    C 实现冒泡排序
    C 实现选择排序
    sqlalchemy orm 操作 MySQL
  • 原文地址:https://www.cnblogs.com/jessie2009/p/9772652.html
Copyright © 2011-2022 走看看