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.
Restrictions:
解题思路:
这道题就是stringbuilder和双指针问题。

代码:
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"
- The string consists of lower English letters only.
- Length of the given string and k will in the range [1, 10000]
解题思路:
这道题就是stringbuilder和双指针问题。

代码:
public String reverseStr(String s, int k) { if(s == null || s.length() <= 1){ return s; } StringBuilder sb = new StringBuilder(); if(s.length() <= k){ int i = s.length() - 1; while(i >= 0){ sb.append(s.charAt(i)); i -= 1; } } else{ int i = 1; while(k * i - 1 <= s.length() - 1){ if(i % 2 == 1){ // reverse here int start = (i - 1) * k; int end = i * k - 1; reverse(sb, s, start, end, true); } else{ // directly append int start = (i - 1) * k; int end = i * k - 1; reverse(sb, s, start, end, false); } i++; } if(i * k - 1 != s.length() - 1){ if((i - 1) % 2 == 0){ // reverse the rest int start = (i - 1) * k; int end = s.length() - 1; reverse(sb, s, start, end, true); } else{ // directly append the rest int start = (i - 1) * k; int end = s.length() - 1; reverse(sb, s, start, end, false); } } } return sb.toString(); } private void reverse(StringBuilder sb, String s, int start, int end, boolean reverse) { if(reverse){ while(start <= end){ sb.append(s.charAt(end)); end--; } } else{ while(start <= end){ sb.append(s.charAt(start)); start++; } } } public static void main(String[] args){ ReverseString2 reverseString2 = new ReverseString2(); String s = "abcdefg"; String rst = reverseString2.reverseStr(s, 2); System.out.println(rst); }

Comments
Post a Comment