242. Valid Anagram QuestionEditorial Solution

来源:互联网 发布:手机淘宝免费注册流程 编辑:程序博客网 时间:2024/06/04 19:16

原题链接:https://leetcode.com/problems/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?

Subscribe to see which companies asked this question

题意:
给你两个字符串s和t,要你写一个函数判断t是否是s的乱序字符串(即字母元素一样,但是字母顺序可能不一样)

思路:
先判断两字符串长度是否相同,
用一个长度为26的int数组来记录t中出现过的字符个数,然后遍历s判断s中的字母是否在t中都有即可。

AC代码:

class Solution {public:    bool isAnagram(string s, string t) {        int letter[26]={0};        if(s.length()!=t.length()) return false;        for(int i=0;i<t.length();i++){            letter[t[i]-'a']++;        }        for(int i=0;i<s.length();i++){            if(letter[s[i]-'a']==0)            return false;            letter[s[i]-'a']--;        }        return true;    }};
0 0
原创粉丝点击