LeetCode#242 Valid Anagram (week5)

来源:互联网 发布:a算法解决八数码问题 编辑:程序博客网 时间:2024/06/03 20:18

week5

题目

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.
原题地址:https://leetcode.com/problems/valid-anagram/description/

解析

题目大意是给两个字符串,判断它们是否一个字符串能否通过打乱顺序得到另一个字符串,是则返回true,反之返回false。注意到Note中提示可以考虑字符串中的字符仅为小写字母,因此字符串中的每个字符只有26种可能。
大致思路为用一个大小为26的int字符串,分别代表a-z,检索两个字符串的每个字符,对第一个字符串中出现的字符,对相应的数组+1,对于第二个字符串中出现的字符,相应数组-1,如果两个字符串仅仅顺序不同,则最终数组的每个元素均为0。

代码

class Solution {public:    bool isAnagram(string s, string t) {        /*如果两个字符串长度不同则可以直接认定两个字符串存在除顺序之外的差别*/        if (s.length() != t.length()) {            return false;        }        int *counter = new int[26];        for (int i = 0; i < 26; ++i) {            counter[i] = 0;        }        for (int i = 0; i < s.length(); ++i) {            int pos1 = (int)(s[i] - 'a');            counter[pos1]++;            int pos2 = (int)(t[i] - 'a');            counter[pos2]--;        }        for (int i = 0; i < 26; ++i) {            if (counter[i] != 0) {                return false;            }        }        return true;    }};