1.特例:全部翻转
比如:goodboy 翻转以后为:yobdoog
思路:就是取得字符串的长度length,然后用一个临时变量做中转两两交换,就是0和最后一个交换,1和倒数第二个交换,依次类推
2.通例:把尾部的n个字符移到字符串的头部
思路:也是用到了两两交换的方法
比如说:要把尾部的3个字符移到头部,先把length-3-1=3,就是索引从0到3的子字符串翻转;然后再把索引是3+1=4到length-1=6的子字符串翻转,最后整体翻转即可
上代码
private static String reserve(String test, int index) { int length = test.length(); int begine = (length - index - 1)%length; char[] chars = test.toCharArray(); turnOver(chars,0,begine); turnOver(chars,begine+1,length-1); turnOver(chars,0,length-1); return new String(chars); } private static void turnOver(char[] chars, int begine, int to) { if(begine < to){ for (; begine < to; begine++,to--) { swap(chars,begine,to); } } } private static void swap(char[] chars, int begine, int to) { char temp = chars[begine]; chars[begine] = chars[to]; chars[to] = temp; }
3.根据某个特定字符进行翻转
比如goodbye 根据d翻转 结果为:yebgood
思路:特定字符左边的子字符串翻转,右边的子字符串也翻转,最后整体翻转
上代码:
//根据某一个特定的字符进行翻转 private static String reserve(String test, char index) { char[] chars = test.toCharArray(); int from = 0,to = 0; for (int i = 0; i < chars.length; i++) { char temp = chars[i]; if(temp == index){ to = i-1; turnOver(chars,from,to); from = i+1; } } if(to < chars.length - 1){ turnOver(chars, from, chars.length-1); } turnOver(chars,0,chars.length-1); return new String(chars); }
注意这个方法也可以 吧 I am a student.按空格进行翻转