阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程
问题理解
你想问的是关于一个循环序列的操作问题。具体来说,你有一个长度为 n 的序列,序列中的字符按大写字母顺序排列,从 'A' 开始。然后你可以对这个序列进行左循环位移或者右循环位移。例如,如果序列是 ABCD,左循环位移 1 位后变成 BCDA,如果再左循环位移 1 位后变成 CDAB。
你想知道如何实现这个功能,特别是在 C# 中。
解决方案
这个问题可以使用模拟的方法来解决。具体来说,我们可以使用一个循环数组来模拟序列的左循环位移和右循环位移。
public static class CircularShift
{
public static string LeftShift(string str, int n)
{
if (string.IsNullOrEmpty(str) || n == 0)
return str;
n = n % str.Length; // 防止 n 大于 str.Length
char[] chars = str.ToCharArray();
Array.Copy(chars, n, chars, 0, str.Length - n);
Array.Copy(chars, 0, chars, str.Length - n, n);
return new string(chars);
}
public static string RightShift(string str, int n)
{
if (string.IsNullOrEmpty(str) || n == 0)
return str;
n = n % str.Length; // 防止 n 大于 str.Length
char[] chars = str.ToCharArray();
Array.Copy(chars, str.Length - n, chars, 0, n);
Array.Copy(chars, 0, chars, n, str.Length - n);
return new string(chars);
}
}
使用示例
string str = "ABCD";
int n = 1;
string leftShifted = CircularShift.LeftShift(str, n);
Console.WriteLine(leftShifted); // 输出: BCDA
string rightShifted = CircularShift.RightShift(str, n);
Console.WriteLine(rightShifted); // 输出: CDAB