本篇同步发布於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
<<: 【Day-28】我们是怎麽开始的?:一间传统软件公司从 0 开始建置的 DevOps 文化(工具篇)- 敏捷看板
>>: 【Day28 】 Wordpress custom field ?是什麽来的?该怎麽用?也许您需要这篇文章的帮助
判断的条件?符合条件执行冒号前:不符合条件执行冒号後 看 w3c setInterval() 的范例...
一日客家话:黑黑的 念法:五无 之前只学过 template literals,tagged tem...
正当磨刀霍霍,打开永丰银行提供的铁人赛专用Spec来试玩金流API时,哇!不得了~总共55页的文件居...
Visual Studio Code 安装:https://code.visualstudio.c...
用免费 Serverless 及 JavaScript 写 Telegram 聊天机器人! 聊天机器...