什么是字谜词
字谜词Anagram是通过重新排列不同单词或短语的字母而形成的单词或短语,通常仅使用一次所有原始字母。
原始单词或短语被称为字谜词的主题。任何以另一种顺序精确再现字母的单词或短语都是字谜词。
例子:
输入: str1 = “listen” str2 = “silent” |
使用排序检查两个字符串是否是彼此的字谜:
对两个给定的字符串进行排序并比较,如果它们相等,则它们是彼此的字谜。
请按照以下步骤实施该想法:-
- 对两个字符串进行排序。
- 比较排序后的字符串:
- 如果它们相等则返回True。
- 否则返回False。
Java:
// JAVA program to check whether two strings |
Python:
class Solution: |
C// C# program to check whether two</strong>
// strings are anagrams of each other
using System;
using System.Collections;
class GFG {
/* 函数,用于检查两个
字符串是否互为拼写字符串*/
public static bool areAnagram(ArrayList str1,
ArrayList str2)
{
// Get lengths of both strings
int n1 = str1.Count;
int n2 = str2.Count;
// If length of both strings is not
// same, then they cannot be anagram
if (n1 != n2) {
return false;
}
// Sort both strings
str1.Sort();
str2.Sort();
// Compare sorted strings
for (int i = 0; i < n1; i++) {
if (str1<i> != str2<i>) {
return false;
}
}
return true;
}
// Driver Code
public static void Main(string[] args)
{
// 创建并初始化新数组列表
ArrayList str1 = new ArrayList();
str1.Add('g');
str1.Add('r');
str1.Add('a');
str1.Add('m');
// create and initialize new ArrayList
ArrayList str2 = new ArrayList();
str2.Add('a');
str2.Add('r');
str2.Add('m');
// Function call
if (areAnagram(str1, str2)) {
Console.WriteLine("The two strings are"
+ " anagram of each other");
}
else {
Console.WriteLine("The two strings are not"
+ " anagram of each other");
}
}
}
Javascript
<script>
// JavaScript program to check whether two strings
// are anagrams of each other
/* function to check whether two strings are
anagram of each other */
function areAnagram(str1,str2)
{
// Get lengths of both strings
let n1 = str1.length;
let n2 = str2.length;
// If length of both strings is not same,
// then they cannot be anagram
if (n1 != n2)
return false;
// Sort both strings
str1.sort();
str2.sort()
// Compare sorted strings
for (let i = 0; i < n1; i++)
if (str1<i> != str2<i>)
return false;
return true;
}
/* Driver Code*/
let str1=['g', 'r', 'a', 'm' ];
let str2=['a', 'r', 'm' ];
// Function Call
if (areAnagram(str1, str2))
document.write("The two strings are"
+ " anagram of each other<br>");
else
document.write("The two strings are not"
+ " anagram of each other<br>");
</script>