[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】我们是怎麽开始的?:一间传统软件公司从 0 开始建置的 DevOps 文化(工具篇)- 敏捷看板

>>:  【Day28 】 Wordpress custom field ?是什麽来的?该怎麽用?也许您需要这篇文章的帮助

【JavaScript】if 的简洁写法| 三元运算子

判断的条件?符合条件执行冒号前:不符合条件执行冒号後 看 w3c setInterval() 的范例...

初学者跪着学JavaScript Day6 :template literals和 tagged template literals傻傻分不清楚

一日客家话:黑黑的 念法:五无 之前只学过 template literals,tagged tem...

[Day 02] 工欲善其事,必先利其器 - [C#]丰收款API必备前置作业(一)

正当磨刀霍霍,打开永丰银行提供的铁人赛专用Spec来试玩金流API时,哇!不得了~总共55页的文件居...

Day29 - 在 Windows 10安装 Rails 开发环境

Visual Studio Code 安装:https://code.visualstudio.c...

#18 用免费 Serverless 及 JavaScript 写 Telegram 聊天机器人!

用免费 Serverless 及 JavaScript 写 Telegram 聊天机器人! 聊天机器...