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?

    Approach 1# Sorting: 

    class Solution {
    public:
        bool isAnagram(string s, string t) {
            if (s.length() != t.length()) return false;
            sort(s.begin(), s.end());
            sort(t.begin(), t.end());
            for (int i = 0; i < s.length(); ++i) {
                if (s[i] != t[i])
                    return false;
            }
            return true;
        }
    };
    
    Runtime: 28 ms

    Approach 2# Hash Table:

    class Solution {
    public:
        bool isAnagram(string s, string t) {
            if (s.length() != t.length()) return false;
            vector<int> temp(26, 0);
            for (int i = 0; i < s.length(); ++i) {
                temp[s[i]-'a']++;
                temp[t[i]-'a']--;
            }
            for (int i = 0; i < 26; ++i) {
                if (temp[i] != 0) return false;
            }
            return true;
        }
    };
    

    Runtime: 8 ms, faster than 83.11% of C++ online submissions for Valid Anagram.

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    JAVA 读取excel文件成List<Entity>
    JAVA 下载单个文件
    js替换指定位置字符串
    Java学习——继承
    Java——单例设计模式
    Java学习——static关键字
    个人成长阶段
    Android_xml背景色的值
    Android开发_关于点击事件
    Android开发_关于中英文切换
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9879861.html
Copyright © 2011-2022 走看看