本篇同步發布於Blog:[解題] LeetCode - 242 Valid Anagram
LeetCode
242 - Valid Anagram
https://leetcode.com/problems/valid-anagram/
給2個字串s和t,求t是否為s的anagram,anagram的定義是一個字串的字母經過不同的排列組合,形成另一個字串。題目保證只有小寫英文字母。
比如範例輸入s = "anagram", t = "nagaram",它們彼此是anagram;但s = "rat", t = "car",並不是anagram,因為t沒有s的r字母、且多了c字母。
建立2個陣列,分別記錄s和t每個a-z字母出現的次數,最後再比對這2個陣列a-z的次數是否相同,相同則代表是anagram。
難度為Easy
#include <iostream>
#include <vector>
using namespace std;
 
class Solution {
public:
    bool isAnagram(string s, string t) {
        vector<int> sCheck(26);
        vector<int> tCheck(26);
        for(int i = 0 ; i < s.length();++i){
            sCheck[s[i] - 'a']++;
        }
 
        for(int i = 0 ; i < t.length();++i){
            tCheck[t[i] - 'a']++;
        }
 
        bool isSame = true;
        for(int i = 0 ; i < 26;++i){
            if(sCheck[i] != tCheck[i]){
                isSame = false;
                break;
            }
        }
 
        return isSame;
    }
};
 
int main() {
	Solution sol;
	cout << sol.isAnagram("anagram", "nagaram") << endl;
	return 0;
}
using System;
using System.Collections.Generic;
namespace LeetCode242
{
	public class Solution {
	    public bool IsAnagram(string s, string t) {
	        List<int> sCheck = new List<int>();
	        List<int> tCheck = new List<int>();
	        for(int i = 0 ; i < 26;++i){
	            sCheck.Add(0);
	            tCheck.Add(0);
	        }
	        
	        for(int i = 0 ; i < s.Length;++i){
	            sCheck[s[i] - 'a']++;
	        }
	        
	        for(int i = 0 ; i < t.Length;++i){
	            tCheck[t[i] - 'a']++;
	        }
	        
	        bool isSame = true;
	        for(int i = 0 ; i < 26;++i){
	            if(sCheck[i] != tCheck[i]){
	                isSame = false;
	                break;
	            }
	        }
	        
	        return isSame;
	    }
	}
	
	public class Program
	{
		public static void Main()
		{
			Solution sol = new Solution();
			Console.WriteLine(sol.IsAnagram("anagram", "nagaram"));
			Console.Read();
		}
	}
}
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%2B%2B/200-299/242.cpp
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%23/200-299/242.cs