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

    题目描述

    Given two strings s and t , 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?

    难度系数

    Medium

    解法一:排序后比较

    class Solution {
    public:
        bool isAnagram(string s, string t) {
            sort(s.begin(),s.end());
            sort(t.begin(),t.end());
            return s==t;
        }
    };

    解法二:记录每个字符串中字母出现的次数

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

     

  • 相关阅读:
    盒子模型中问题
    outline
    高度自动相等方法
    正则表达式
    绝对定位 相对定位
    replace 使用函数作为第二参数
    float 浮动
    line-height 行高
    元素隐藏
    现代浏览器内部
  • 原文地址:https://www.cnblogs.com/AntonioSu/p/12741562.html
Copyright © 2011-2022 走看看