iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 29
1
自我挑戰組

神羅天征! 一起(爆肝)征服程式解題系列 第 29

[Day 29] LeetCode - 242 Valid Anagram

本篇同步發布於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

程式碼 (C++ 與 C#):

#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();
		}
	}
}

GITHUB位置(C++ 與 C#):

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


上一篇
[Day 28] LeetCode - 387 First Unique Character in a String
下一篇
[Day 30] LeetCode - 125 Valid Palindrome
系列文
神羅天征! 一起(爆肝)征服程式解題30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言