Leetcode-541. Reverse String II

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。这次比赛略无语,没想到前3题都可以用暴力解。

博客链接:mcf171的博客

——————————————————————————————


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:
  1. The string consists of lower English letters only.
  2. Length of the given string and k will in the range [1, 10000]
这个题目挺简单的,但是一开始有一个地方写的有一点问题,导致错了一次。
public class Solution {
    public String reverseStr(String s, int k) {
        StringBuilder sb = new StringBuilder("");
        int start = 0;
        while(start <= s.length()){
            int i = 0,j = 0;
            if(s.length() - start <= k){
                i = s.length() - 1;
                j = s.length();
            }else{
                i = start + k - 1;
                j = start + k;
            }
            for( ;i >= start; i--) sb.append(s.charAt(i));
            for(; j < s.length() && j < start + 2*k; j ++)sb.append(s.charAt(j));
            start += 2*k;
        }
        
        return sb.toString();
    }
}




你可能感兴趣的:(算法)