力扣题目链接
基础知识
class Solution { public String reverseStr(String s, int k) { StringBuffer res = new StringBuffer(); int length = s.length(); int start = 0; while(start<length){ //找到k处和2k处 StringBuffer temp = new StringBuffer(); //与length进行判断,如果大于length,就将其置为length int firstK = (start+k>length) ? length : start + k; int secondK = (start+2*k>length) ? length : start +2*k; //无论start在什么位置,至少反转一次 temp.append(s.substring(start,firstK)); res.append(temp.reverse()); //如果firstK与secondK之间有元素,这些元素可以直接存入res if(firstK<secondK){ res.append(s.substring(firstK,secondK)); } start += (2*k); } return res.toString(); } }
class Solution { public String reverseStr(String s, int k) { char[] ch = s.toCharArray(); for(int i = 0; i < ch.length; i += 2 * k){ int start = i; //这里是判断尾数够不够k个来取决end指针的位置 int end = Math.min(ch.length - 1, start + k - 1); //用异或运算反转 while(start < end){ ch[start] ^= ch[end]; ch[end] ^= ch[start]; ch[start] ^= ch[end]; start++; end--; } } return new String(ch); } }