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
  • 相关阅读:
    selenium 浏览器操作
    selenium 4.0新特性及新旧api对比
    Selenium123介绍
    selenium元素定位(三) css定位方法
    selenium 安装和启动
    Selenium元素定位(一)30+1+5种方式
    软件开发经验收集
    spring+hibernate架构中Dao访问数据库的几种方法
    某励志书4
    PHP的Foreach
  • 原文地址:https://www.cnblogs.com/immjc/p/7192079.html
Copyright © 2011-2022 走看看