zoukankan      html  css  js  c++  java
  • [Algorithm] 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?

    /**
     * @param {string} s
     * @param {string} t
     * @return {boolean}
     */
    var isAnagram = function(s, t) {
        
        if (s == undefined || t == undefined) {
            return false;
        }
        
        if (s.length === 0 && t.length === t) {
            return true;
        }
        
        if (s.length !== t.length) {
            return false;
        }
        
        let hashed = {}
        for (let i = 0; i < s.length; i++) {
            let char = s[i];
            if (char in hashed) {
                hashed[char]++
            } else {
                hashed[char] = 1;
            }
    
            let charT = t[i];
            if (charT in hashed) {
                hashed[charT]--;
            } else {
                hashed[charT] = -1;
            }
        }
        
        for (let value of Object.values(hashed)) {
            if (value !== 0) {
                return false;
            }
        }
        
        return true;
    };
  • 相关阅读:
    并发编程3
    并发编程2
    4/23
    4/22
    并发编程1
    粘包问题
    Navicat12激活
    IDEA创建maven项目报错解决:Failed to create a Maven project: 'C:/Users/../IdeaProjects/../pom.xml' already e
    IDEA
    windows下查看端口运行情况--解决端口冲突问题
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12013011.html
Copyright © 2011-2022 走看看