思想总结:首先将字符串转变为字符数组,再进行遍历并反转字符。
1.反转字符串
代码:
class Solution {public void reverseString(char[] s) {reverse(s,0,s.length); //左闭右开}public static void reverse(char[] ch,int i,int j) { 翻转函数j = j-1;while(i<j) {char tmp = ch[i];ch[i] = ch[j];ch[j] = tmp;i++;j--;}}
}
2.反转字符串 ||
代码:
class Solution {public String reverseStr(String s, int k) {char[] arr = s.toCharArray(); //先将字符串 转换为 字符数组for(int i=0;i<s.length();i+=2*k) {if(i+k <= s.length()) { //剩余的字符个数肯定大于kreverse(arr,i,i+k); //左开右闭}else{reverse(arr,i,s.length()); //左开右闭 剩余字符少于k个的情况} }return new String(arr);}public static void reverse(char[] ch,int i,int j) { //翻转函数j = j-1;while(i<j) {char tmp = ch[i];ch[i] = ch[j];ch[j] = tmp;i++;j--;}}
}
3.反转字符串中的单词 |||
可以双指针 也可以用栈来做
代码:
class Solution {/* //第一种 双指针public String reverseWords(String s) {char[] ch = s.toCharArray();int left = 0; // left保存每一次翻转的最开始位置int right=0; // right 保存每一次反转的结束位置for(;right<ch.length;right++) {if(ch[right]==' ') {reserve(ch,left,right); //左开右闭left = right+1;}}reserve(ch,left,right); //翻转最后一组字符串return new String(ch); //字符数组转换为字符串}public static void reserve(char[] ch,int i ,int j) { //自定义翻转函数j = j-1;while(i<j) {char tmp = ch[i];ch[i] = ch[j];ch[j] = tmp;i++;j--;}}*///2. 用栈来做public String reverseWords(String s) {Stack<Character> stack = new Stack<>();char[] ch = s.toCharArray();StringBuilder sb = new StringBuilder();for(int i = 0;i<ch.length;i++) {if(ch[i]!=' ') {stack.push(ch[i]);}else{while(!stack.isEmpty()) {sb.append(stack.pop());}sb.append(' ');}}while(!stack.isEmpty()) {sb.append(stack.pop());}return sb.toString();}}