反转字符串 II (Reverse String II)

 

思路:

// @Title: 反转字符串 II (Reverse String II)
// @Author: qisiii
// @Date: 2024-09-12 20:52:20
// @Runtime: 1 ms
// @Memory: 42.4 MB
// @comment: 
// @flag: 
class Solution {
    public String reverseStr(String s, int k) {
        char[] arr=s.toCharArray();
        for(int i=0;i<arr.length;i=i+2*k){
                int start=i;
                //本来应该是到i+K为止,但是加入越界了,那么就只是到末尾;
                int end=i+k-1;
                if(end>=s.length()){
                    end=s.length()-1;
                }
                while(start<end){
                    char temp=arr[start];
                    arr[start]=arr[end];
                    arr[end]=temp;
                    start++;end--;
                }
        }

        return new String(arr);
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18