题目描述
- 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如输入字符串"abcdefg"和数字2,该函数将返回左旋转2位得到的结果"cdefgab"。
算法分析
- 分两段各做一次翻转,再做一次总的翻转。
提交代码:
class Solution {
public:
string LeftRotateString(string str, int n) {
if (n >= str.length() || n < 1)
return str;
Reverse(str.begin(), str.begin() + n - 1);
Reverse(str.begin() + n, str.end() - 1);
Reverse(str.begin(), str.end() - 1);
return str;
}
void Reverse(string::iterator beg, string::iterator end)
{
while (beg < end)
{
swap(*beg, *end);
++beg, --end;
}
}
};
测试代码:
// ====================测试代码====================
void Test(const char* testName, string input, int num, string expectedResult)
{
if (testName != nullptr)
printf("%s begins: ", testName);
Solution s;
string result = s.LeftRotateString(input, num);
if (result == expectedResult)
printf("Passed.\n\n");
else
printf("Failed.\n\n");
}
// 功能测试
void Test1()
{
string input = "abcdefg";
string expected = "cdefgab";
Test("Test1", input, 2, expected);
}
// 边界值测试
void Test2()
{
string input = "abcdefg";
string expected = "bcdefga";
Test("Test2", input, 1, expected);
}
// 边界值测试
void Test3()
{
string input = "abcdefg";
string expected = "gabcdef";
Test("Test3", input, 6, expected);
}
// 鲁棒性测试
void Test4()
{
Test("Test4", string(), 6, string());
}
// 鲁棒性测试
void Test5()
{
string input = "abcdefg";
string expected = "abcdefg";
Test("Test5", input, 0, expected);
}
// 鲁棒性测试
void Test6()
{
string input = "abcdefg";
string expected = "abcdefg";
Test("Test6", input, 7, expected);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
return 0;
}