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?

    使用一个map存储s中字母及其出现的次数,通过map查找t中元素是否出现,如果出现则让它在m中的出现次数-1,如果没有出现,则返回false。最后判断map中的值是否全部为0,如果是则证明两个字符串是有效的,否则返回false。

    class Solution {
    public:
        bool isAnagram(string s, string t) {
            unordered_map<char, int> m;
            for (char c : s)
                m[c]++;
            for (int i = 0; i != t.size(); i++) {
                if (m.count(t[i]))
                    m[t[i]]--;
                else
                    return false;
            }
            for (auto it = m.begin(); it != m.end(); it++) {
                if (it->second != 0)
                    return false;
            }
            return true;
        }
    };
    // 19 ms

     也可以先对两个字符串进行排序,比较排序后的字符串,如果相同返回true,如果不同返回false。

    class Solution {
    public:
        bool isAnagram(string s, string t) {
            sort(s.begin(), s.end());
            sort(t.begin(), t.end());
            if (s == t)
                return true;
            else
                return false;
        }
    };
    // 23 ms
  • 相关阅读:
    shell:读取文件的每一行内容并输出
    shell中set命令
    shell中declare命令
    MySQL MID()函数用法
    mysql的取整函数
    二分查找算法
    zookeeper安装和使用
    Redis 集群--------Redis-cluster
    ehcahe + redis 实现多级缓存
    Redis事物
  • 原文地址:https://www.cnblogs.com/immjc/p/7192079.html
Copyright © 2011-2022 走看看