242. Valid Anagram

2018/04/13 leetcode 共 649 字,约 2 分钟

Title

the problem link

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?

题目大意:判断一个字符串是不是另一个字符串的改变了位置的字符串,就是统计每个字符串的个数,都一样就true

Solution

//cpp:
class Solution {
public:
	bool isAnagram(string s, string t) {
		int num[256];
		fill(num, num + 256, 0);
		if (s.length() != t.length())
			return false;
		for (int i = 0; i < s.length(); i++) {
			num[s[i]]++;
			num[t[i]]--;
		}
		for (int i = 0; i < 256; i++) {
			if (num[i] != 0)
				return false;
		}
		return true;
		
	}
};

Search

    Table of Contents