leetcode541. Reverse String II
来源:互联网 发布:苏州java软件开发招聘 编辑:程序博客网 时间:2024/06/03 11:41
541. Reverse String II
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 = 2Output: "bacdfeg"
Restrictions:
The string consists of lower English letters only.
Length of the given string and k will in the range [1, 10000]
解法
i = i + 2 * k
临界点:i + k - 1和arr.length的长度比较。
如果k >= arr.length,则0 ~ arr.length-1全部反转;
如果i+k-1 < arr.length, 则0 ~ i+k-1全部反转;
如果i+k-1 >= arr.length, 则0 ~ arr.length-1全部反转。
综上,每次取min(i + k -1, arr.length-1)作为反转的右侧边界。
public class Solution { public String reverseStr(String s, int k) { if (s == null || s.length() == 0) { return ""; } char[] arr = s.toCharArray(); int length = arr.length; for (int i = 0; i < length; i = i + 2 * k) { int n = Math.min(i + k - 1, length - 1); reverse(arr, i, n); } return new String(arr); } public void reverse(char[] s, int left, int right) { while (left < right) { char temp = s[left]; s[left] = s[right]; s[right] = temp; left++; right--; } }}
阅读全文
0 0
- leetcode541. Reverse String II
- leetcode541 Reverse StringII java
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- Reverse String II
- Reverse String II
- Reverse String II
- oj541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- Reverse String II
- java-面试题
- Android 文件打开方法
- 新手使用PHP制作日历
- Spark性能调优(一)
- C++标准库笔记:13.11 String Stream Classes
- leetcode541. Reverse String II
- 包的使用
- Spring框架bean的scope属性
- Python中switch结构的实现
- 使用PHP制作计算器
- jvm常用工具-jps
- org.hibernate.PropertyAccessException: Null value was assigned to a property报错问题
- javaBean转为json
- 使用python备份博客图床图片