您的位置:首页 > 其它

242. Valid Anagram

2016-05-14 14:35 190 查看

242. Valid Anagram

Description:

Given two strings s and t, write a function to determine if t is an anagram of s.

note:

You may assume the string contains only lowercase alphabets.

Example:

For example,

s = “anagram”, t = “nagaram”, return true.

s = “rat”, t = “car”, return false.

Link:

https://leetcode.com/problems/valid-anagram/

Analysis:

这道题至少有两种思路:

A. 分别统计字符串s和t中每个字母出现的频率,若相同,则认为两个字符串是由字母顺序颠倒构成的。

B. 在s和t长度相同的情况下,分别找出在字符串s中和t对应的每一个字母,如果每个字母都完全对应,则认为他们是由字母顺序颠倒构成的。

对应这两种思路共有两种方法,见源码。

Source Code(C++):

#include <iostream>
#include <string>
#include <vector>
using namespace std;

/********************************分别统计s和t中字母出现的频率到数组中,比较各个字母出现的频率从而得出结果***********************************************/
/*
class Solution {
public:
bool isAnagram(string s, string t) {
vector<int> s_alphabet(26, 0), t_alphabet(26, 0);
for (int i=0; i<s.length(); i++) {
s_alphabet.at(s.at(i)-97)++;
}
for (int i=0; i<t.length(); i++) {
t_alphabet.at(t.at(i)-97)++;
}
for (int i=0; i<s_alphabet.size(); i++){
if (s_alphabet.at(i) != t_alphabet.at(i)) {
return false;
}
}
return true;
}
};
*/
/********************************直接将s中的每一个字母与t比对***********************************************/
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() !=t.length()) {
return false;
}
else {
for (int i=0; i<s.length(); i++) {
int ind = t.find(s.at(i));
if (ind == string::npos) {
return false;
}
else {
t.erase(ind, 1);
}
}
return true;
}
}
};

int main() {
Solution sol;
cout << sol.isAnagram("anagram", "nagaram");
cout << sol.isAnagram("rat", "car");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: