字符串反转算法题
今天聊一聊之前练过的算法题,有个学弟问我,我讲完了然后整理了整理,贴到博客园里:
字符串反转 比如 “我爱你”,成了 “你爱我”
哈哈哈,废话不多说,先哔哔下思路:
I love you 应该这么玩儿 先把整个字符串 反转 uoy evol I 然后根据空格分出单词 单词再逐个 反转 you love I
秒懂了吧?
闲言碎语不要讲,上代码:
package TT; public class Test1 { public static void rotateWord(char[] chas){ if(chas.length ==0 || chas==null){ return; } reverse(chas, 0, chas.length-1); int l =-1; int r = -1; for(int i =0; i<chas.length; i++){ if(chas[i] !=' '){ l = i ==0 ||chas[i-1]==' ' ? i : l; r = i ==chas.length-1 || chas[i+1] ==' ' ? i:r; } if(l!=-1 && r!=-1){ reverse(chas,l,r); l = -1; r =-1; } } } public static void reverse(char[] chas, int start, int end){ char tmp = 0; while(start <end){ tmp = chas[start]; chas[start]=chas[end]; chas[end]=tmp; start++; end--; } } public static void main(String[] args){ String a ="I love you"; char[] b = a.toCharArray(); System.out.println(a); rotateWord(b); String c = String.valueOf(b); System.out.println(c); } }
测试结果:
public class t1 { public static String revert(String string) { char[] chars = string.toCharArray(); int left = 0; int right = chars.length - 1; while (left != right && left<=right && right>=0) { swap(left, right, chars); left++; right--; } String result = new String(chars); return result; } public static void swap(int x , int y , char[] chars){ char temp = '\u0000'; temp = chars[x]; chars[x] = chars[y]; chars[y] = temp; } public static void main(String[] args){ String testStr = "123456789"; String revertResult = revert(testStr); System.out.println(revertResult); } }
这个解法主要在于while的控制, left<= right