LeetCode 541. Reverse String II (字串翻轉)
阿新 • • 發佈:2019-01-10
Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.
Example:
Input: s = "abcdefg", k = 2 Output: "bacdfeg"Restrictions:
- The string consists of lower English letters only.
- Length of the given string and k will in the range [1, 10000]
輸入字串s和正整數k,對於每2k個字母,將其中前k個字母翻轉。最後如果剩餘字母少於k個,則將其全部翻轉;若多於k個,則將前k個翻轉,其餘不變。
思路:利用void reverse(str.begin(),str.end())函式直接原位翻轉,若要翻轉到其他變數,可使用str2.assign(str.rbegin(), str.rend())函式。
string reverseStr(string s, int k) { int left = s.size()%(2*k); int i; if (left<k) { for(i=0;i<s.size()-left;i+=(2*k)) reverse(s.begin()+i,s.begin()+i+k); reverse(s.begin()+i,s.end()); } else { for(i=0;i<s.size()-left;i+=(2*k)) reverse(s.begin()+i,s.begin()+i+k); reverse(s.begin()+i,s.begin()+i+k); } return s; }