LeetCode知识点总结 - 541
LeetCode 541. Reverse String II
| 考点 | 难度 |
|---|---|
| String | Easy |
题目
Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.
If there are fewer 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 leave the other as original.
思路
Step through the string 2k characters at a time : reverse first k, leave next k untouched, repeat
答案
publicclassSolution{publicStringreverseStr(Strings,intk){char[]arr=s.toCharArray();intn=arr.length;inti=0;while(i<n){intj=Math.min(i+k-1,n-1);swap(arr,i,j);i+=2*k;}returnString.valueOf(arr);}privatevoidswap(char[]arr,intl,intr){while(l<r){chartemp=arr[l];arr[l++]=arr[r];arr[r--]=temp;}}}