题目:字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如输入字符串"abcdefg"和数字2,该函数将返回左旋转2位得到的结果"cdefgab".
核心代码:
<pre><code>`
func reversePosition(strArr:inout [Character],begin:Int,end:Int) {
var low:Int = begin
var high:Int = end
while low < high {
swap(&strArr[low], &strArr[high])
low += 1
high -= 1
}
}
func leftRoateString(str:String,len:Int) -> String {
var strArr:[Character] = [Character]()
for c in str.characters {
strArr.append(c)
}
reversePosition(strArr: &strArr, begin: 0, end: len - 1)
reversePosition(strArr: &strArr, begin: len, end: strArr.count - 1)
reversePosition(strArr: &strArr, begin: 0, end: strArr.count - 1)
return String(strArr)
}`</code></pre>
测试代码:
<pre><code>var roateResult:String = reverseString.leftRoateString(str: "abcdefg", len: 2) print("FlyElephant-左旋转之后的字符串---\(roateResult)")
</code></pre>