摘自https://github.com/julycoding/The-Art-Of-Programming-by-July
第一篇:旋转字符串
1, 暴力移位法 改成c#的试下:
public static void Main(string[] args)
{
var result= LeftRotateString("abcdefg", 2);
}
public static string LeftShiftOne(string s, int n)
{
char firstLetter = s[0];
string result = string.Empty;
for (int i = 0; i < n-1; i++)
{
result += s[i + 1];
}
result += firstLetter;
return result;
}
public static string LeftRotateString(string s, int m)
{
var n = s.Length;
while (m-- > 0)
{
s = LeftShiftOne(s, n);
}
return s;
}```
2 , 三步反转法
```csharp
public static string LeftRotateString_method2(string s, int m)
{
var n = s.Length;
m = m % n;
var s1 = ReverseString(s, 0, m - 1);
var s2 = ReverseString(s1,m,n - 1);
var s3 = ReverseString(s2, 0,n - 1);
return s3;
}
public static string ReverseString(string s, int from, int to)
{
StringBuilder sb = new StringBuilder(s);
while (from < to)
{
char t = sb[from];
sb[from++] = sb[to];
sb[to--] = t;
}
return sb.ToString();
}