LeetCode 541. Reverse String II
原题链接在这里:https://leetcode.com/problems/reverse-string-ii/#/description
题目:
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]
题解:
是Reverse String的进阶题目.
每2k个char中前k个char swap.
Time Complexity: O(n), n = s.length(). Space: O(n).
AC Java:
1 public class Solution { 2 public String reverseStr(String s, int k) { 3 int len = s.length(); 4 char [] charArr = s.toCharArray(); 5 int i = 0; 6 while(i < len){ 7 int j = Math.min(i+k-1, len-1); 8 swap(charArr, i, j); 9 i += 2*k; 10 } 11 12 return new String(charArr); 13 } 14 15 private void swap(char [] s, int i, int j){ 16 while(i<j){ 17 char temp = s[i]; 18 s[i] = s[j]; 19 s[j] = temp; 20 i++; 21 j--; 22 } 23 } 24 }
AC C++:
1 class Solution { 2 public: 3 string reverseStr(string s, int k) { 4 int i = 0; 5 int n = s.size(); 6 while(i < n){ 7 int j = min(n - 1, i + k - 1); 8 int next_i = i + 2 * k; 9 while(i < j){ 10 swap(s[i], s[j]); 11 i++; 12 j--; 13 } 14 15 i = next_i; 16 } 17 18 return s; 19 } 20 };