標籤:eve get 尾到頭 思路 input [] cti 倒序 blog
轉載請註明原文地址:http://www.cnblogs.com/ygj0930/p/6410409.html
6:Reverse String
Write a function that takes a string as input and returns the string reversed.
此題:字串反轉題。
思路:此題大一學C++的時候上機題就做過了,當時思路是:把String轉化為char[],從尾到頭遍曆一次倒序地把字元複製到另一個數組(從頭到尾),然後把新數組toString()即可。現在用Java做的話,把新數組換成用StringBuffer代替,倒序遍曆char[]逐個append到buffer,然後toString()即可。由於每個元素都遍曆了一次,複雜度O(n)。
public String reverseString(String s) { char[] chars=s.toCharArray(); StringBuffer buffer=new StringBuffer(); for(int i=chars.length-1;i>=0;--i){ buffer.append(chars[i]); } return buffer.toString(); }
第二種思路是:把char[]的前後半交換即可,只需遍曆一半,複雜度O(n/2)。
public String reverseString(String s) { char[] chars=s.toCharArray(); int half=chars.length/2; for(int i=0;i<half;++i){ char temp=chars[chars.length-1-i]; chars[chars.length-1-i]=chars[i]; chars[i]=temp; } //這裡注意:char[]轉化為String是通過new String(char[])實現的 return new String(chars); }
【leetcode】solution in java——Easy2