LeetCode:Reverse String II
阿新 • • 發佈:2018-12-15
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]
import java.util.LinkedList; /** * @author zhangyu * @version V1.0 * @ClassName: ReverseString2Test * @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. * @date 2018/10/14 15:34 **/ public class ReverseString2Test { public static void main(String[] args) { String s = "abcdefg"; int key = 2; String newString = getReverseString2(s, 2); System.out.println(newString); } private static String getReverseString2(String s, int k) { //當s字串的長度小於k的值 if (s.length() <= k) { return new StringBuffer(s).reverse().toString(); } //當s字串的長度介於 k和2k之間 if (s.length() > k && s.length() <= 2 * k) { String subString = s.substring(0, k); subString = new StringBuffer(subString).reverse().toString(); return subString + s.substring(k, s.length()); } //當k的字串的長度大於2k if (s.length() > 2 * k) { LinkedList<String> list = new LinkedList<>(); StringBuffer sb = new StringBuffer(); int number = s.length() / k; for (int i = 0; i < number; i++) { list.add(s.substring(i * k, i * k + k)); } if (number * k < s.length()) { list.add(s.substring(number * k)); } for (int index = 0; index < list.size(); index++) { if (index % 2 == 0) { String temp = new StringBuffer(list.get(index)).reverse().toString(); sb.append(temp); } else { sb.append(list.get(index)); } } return sb.toString(); } return null; } }