题目描述
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
示例 1:
- 输入: s = “abcdefg”, k = 2
- 输出: “cdefgab”
示例 2:
- 输入: s = “lrloseumgh”, k = 6
- 输出: “umghlrlose”
限制:
- 1 <= k < s.length <= 10000
难度: 简单
题解
方法一: String.Substring
步骤:
- Substring(n):从n开始检索到字符串末尾;
- Substring(0,n) :从0开始检索到n;
- 把第二步检出的结果加到第一步检出的结果后面。
String.Substring 方法
命名空间:System
程序集:mscorlib.dll, System.Runtime.dll
作用: 获得子字符串
重载:
- Substring(Int32):
从此实例检索子字符串。 子字符串在指定的字符位置开始并一直到该字符串的末尾。 - Substring(int startIndex, int length)
从此实例检索子字符串。 子字符串从指定的字符位置开始且具有指定的长度。
startIndex: 此实例中子字符串的起始字符位置(从零开始)。
length:子字符串中的字符数。
C#:
public class Solution {
public string ReverseLeftWords(string s, int n)
{
return s.Substring(n, s.Length - n)+s.Substring(0, n); // 两子字符串用+号连接
// return s.Substring(n) + s.Substring(0, n); // 这种更简便
}
}
等价于
public class Solution
{
public string ReverseLeftWords(string s, int n) => s.Substring(n, s.Length - n)+s.Substring(0, n); // =>: 函数返回值
}
方法二:String.Remove + String.Substring
步骤:
- s.Remove(0, n):将字符串s 的前 n 个字符删除,得到第一个子字符串
- s.Substring(0, n):获得要转移的子字符串
- s.Remove(0, n) + s.Substring(0, n):拼接两字符串。
String.Remove 方法
命名空间: System
程序集: mscorlib.dll, System.Runtime.dll
作用:返回一个新字符串,它相当于从当前字符串删除了指定数量的字符。
重载:
- Remove(Int32)
返回当前实例中从指定位置到最后位置的所有以删除的字符的新字符串。 - Remove(int startIndex, int count)
返回指定数量字符在当前这个实例起始点在已删除的指定的位置的新字符串。
startIndex: 开始删除字符的从零开始的位置。
count:要删除的字符数。
public class Solution {
public string ReverseLeftWords(string s, int n)
{
return s.Remove(0, n) + s.Substring(0, n);
}
}
方法三:循环
低效, 不推荐
C#:
public class Solution {
public string ReverseLeftWords(string s, int n)
{
string str = "";
for(int i = n;i < s.Length;i ++)
{
str += s[i];
}
for(int i = 0;i < n;i ++)
{
str += s[i];
}
return str;
}
}
方法四:StringBuilder.Append
此方法类似于方法三。
StringBuilder 类
命名空间:System.Text
程序集:mscorlib.dll, System.Runtime.dll
作用:表示可变字符字符串。 此类不能被继承。此类表示一个类似字符串的对象,其值为可变字符序列。
String 和 StringBuilder 的区别:
- String:是不可变类型。
出现的用于修改对象的每个操作 String 实际上都会创建一个新的字符串。 - StringBuilder:是一个可变字符串类。
可变性是指在创建类的实例后,可以通过追加、移除、替换或插入字符来修改它。
StringBuilder.Append 方法
命名空间:System.Text
程序集:mscorlib.dll, System.Runtime.dll
作用:向此实例追加指定对象的字符串表示形式。
C#:
public class Solution {
public string ReverseLeftWords(string s, int n)
{
int len = s.Length;
StringBuilder ans = new StringBuilder();
for(int i = n; len > i; ++i)
{
ans.Append(s[i]);
}
for(int i = 0; n > i; ++i)
{
ans.Append(s[i]);
}
return ans.ToString(); // 注意转换成string类型。
}
}