题解 | #字符串反转# 四种方法
字符串反转
https://www.nowcoder.com/practice/e45e078701ab4e4cb49393ae30f1bb04
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); //方法1:投机取巧 //System.out.println(new StringBuilder(str).reverse().toString()); //方法2:单指针 /* char[] charArr = str.toCharArray(); int len = str.length(); for(int i=0; i<len; i++){ charArr[i] = str.charAt(len-i-1); } System.out.println(new String(charArr)); */ //方法3:双指针 char[] charArr = str.toCharArray(); int left = 0; int right = str.length() - 1; while(left < right){ char temp = charArr[left]; charArr[left] = charArr[right]; charArr[right] = temp; left++; right--; } System.out.println(new String(charArr)); //方法4:递归 //System.out.println(reverse(str)); } public static String reverse(String s){ if(s==null || s=="" || s.length()==0){ return s; }else{ return reverse(s.substring(1)) + s.charAt(0); //s.substring(1)从下标位置1截取到s尾 //s.charAt(0)返回下标位置0处的字符 } } }