CShap 一个字符串是否是另一个字符串的排列 源代码
时间: 2023-10-02 09:10:12 浏览: 37
以下是C#代码,用于检查一个字符串是否是另一个字符串的排列:
```csharp
using System;
public class Program
{
public static bool IsPermutation(string str1, string str2)
{
if (str1.Length != str2.Length)
return false;
int[] charCount = new int[256];
for (int i = 0; i < str1.Length; i++)
charCount[str1[i]]++;
for (int i = 0; i < str2.Length; i++)
{
charCount[str2[i]]--;
if (charCount[str2[i]] < 0)
return false;
}
return true;
}
public static void Main()
{
string str1 = "abcde";
string str2 = "edcba";
if (IsPermutation(str1, str2))
Console.WriteLine("'{0}' is a permutation of '{1}'", str1, str2);
else
Console.WriteLine("'{0}' is not a permutation of '{1}'", str1, str2);
}
}
```
该代码使用一个整数数组来计数每个字符在第一个字符串中出现的次数。然后,它遍历第二个字符串并递减相应字符的计数器。如果在任何时候计数器变为负数,则第二个字符串不是第一个字符串的排列,因此该函数将返回false。否则,如果在遍历第二个字符串后所有字符的计数器都为零,则第二个字符串是第一个字符串的排列,因此该函数将返回true。