今天刷到一题反转串,代码简洁,甚是喜欢
我们把“cba”称为“abc”的反转串。
求一个串的反转串的方法很多。下面就是其中的一种方法,
public class reverseString {
public static String reverseString(String x)
{
if(x==null || x.length()<2) return x;
return reverseString(x.substring(1))+x.charAt(0);
}
}
怎么样,迭代真是牛X;作为java刚出道的菜鸟就喜欢这种“骚操作”
测试:
public static void main(String[] args) {
String s="abcswecsdcsdc";
System.out.println(reverseString(s));
}
强行解释一波(大佬绕路): reverseString方法就是用迭代和字符串切割完成;比如String s = “abc” 先substring(1)获得 “bc” reverseString(bc)+“a”,在reverseString© +“b”;迭代的结果就是:
reverseString©+“b”+“a” if判断reverseString©返回c ,得到“cba”。