标签:style blog http color os io strong ar
代码实现:
1 // 26.cc 2 #include <iostream> 3 #include <string> 4 #include <cstring> 5 using namespace std; 6 7 // 反转字符串 8 void reverse_str(char* start, char* end) { 9 if (!start || !end) 10 return; 11 while (start < end) { 12 swap(*start, *end); 13 start++; 14 end--; 15 } 16 } 17 18 // 左移k个字符 19 void left_rotate_str(char*& str, size_t k) { 20 if (!str || k <= 0) 21 return; 22 23 size_t n = strlen(str); 24 k = k % n; 25 26 reverse_str(str, str + k - 1); 27 reverse_str(str + k, str + n - 1); 28 reverse_str(str, str + n - 1); 29 } 30 31 int main() { 32 cout << "input a str:" << endl; 33 34 string s; 35 getline(cin, s); 36 37 char* str = new char[s.size() + 1]; 38 strcpy(str, s.c_str()); 39 int k = 5 < s.size() ? 5 : 0; 40 left_rotate_str(str, k); 41 42 cout << "after left rotate " << k << " chars:" << endl << str << endl; 43 return 0; 44 }
输出:
$ ./a.exe input a str: 12345678 after left rotate 5 chars: 67812345
IT公司100题-26-左旋转字符串,布布扣,bubuko.com
标签:style blog http color os io strong ar
原文地址:http://www.cnblogs.com/dracohan/p/3927548.html