题目地址: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]
一种比较好的写法(当然换成字符数组交换顺序就更好了)
class Solution { public String reverseStr(String s, int k) { StringBuilder str = new StringBuilder(); int len = s.length(); int num = 0; for (int i = 0; i < len; i += k) { if ((num & 1) == 0) { str.append(new StringBuilder(s.substring(i, Math.min(i + k, len))).reverse()); } else { str.append(s.substring(i, Math.min(i + k, len))); } ++num; } return new String(str); } }
Debug code in playground:
class Solution { public String reverseStr(String s, int k) { StringBuilder str = new StringBuilder(); int len = s.length(); int num = 0; for (int i = 0; i < len; i += k) { if ((num & 1) == 0) { str.append(new StringBuilder(s.substring(i, Math.min(i + k, len))).reverse()); } else { str.append(s.substring(i, Math.min(i + k, len))); } ++num; } return new String(str); } } public class MainClass { public static String stringToString(String input) { if (input == null) { return "null"; } return Json.value(input).toString(); } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = in.readLine()) != null) { String s = stringToString(line); line = in.readLine(); int k = Integer.parseInt(line); String ret = new Solution().reverseStr(s, k); String out = (ret); System.out.print(out); } } }
以下是最初自己想到的糟糕算法,勉强能解决
class Solution { public String reverseStr(String s, int k) { StringBuilder s1 = new StringBuilder(s); int n = k; StringBuilder ss = new StringBuilder(); if (n == 1) { return s; } else { if (s.length() < n) { return new String(s1.reverse()); } else { int t1 = 0, t2 = 0, num = n - 1, temp = 0; boolean flag = true; int len = s.length(); for (int i = 0; i < len; ++i) { if (t1 <= num) { ++t1; t2 = 0; if (flag) { temp = i + num; flag = false; } if (temp < len) { // 剩下的足够k ss.append(s1.charAt(temp--)); } else { // 剩下的不足k for (int j = len - 1; j >= i; --j) { ss.append(s1.charAt(j)); } break; } } else if (t2 <= num) { flag = true; ++t2; ss.append(s1.charAt(i)); } if (t2 == n) { t1 = 0; } } } return new String(ss); } } }
========================================Talk is cheap, show me the code=======================================