字符反转排序

来源:互联网 发布:linux退出目录命令 编辑:程序博客网 时间:2024/05/18 00:26

title:Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".

以下的method1是我自己写的,最low的一种。2,3都是调用系统api实现。


public String reverseString(String s) {        //METHOD1  11ms        // StringBuilder sb = new StringBuilder();        // int len = s.length();        // String [] arr = new String[len];        // for(int i = 0; i < len; i++){        //     int count = i;        //     arr[i] = s.substring(count,count + 1);        // }                // for(int j = arr.length - 1; j >= 0; j--){        //     sb.append(arr[j]);        // }                // return s = sb.toString();                //METHOD2  5ms        //  return new StringBuilder(s).reverse().toString();                //METHOD3 5ms        StringBuilder sb = new StringBuilder();        char tmpChar ;        for(int i = s.length() - 1; i >= 0; i-- ){            tmpChar = s.charAt(i);            sb.append(tmpChar);        }        return sb.toString();            }

然后是别人给出的更优方法:循环只遍历一半,时间效率就提高上去了。值得学习。

public String reverseString(String s) {        char[] array=s.toCharArray();        for(int i=0;i<array.length/2;i++){            char temp=array[i];            array[i]=array[array.length-i-1];            array[array.length-i-1]=temp;                    }        return new String(array);    }

最后一种给出了更优的方案:

解释:pulling you temp variable out of the for loop can reduce the time to 2ms, like my code as follows, because temp is a temporary variable it is unnecessarily declared so many times:

public String reverseString(String s) {char[] charArray = s.toCharArray();char temp;int len = charArray.length;for (int idx = 0; idx < len / 2; idx++) {temp = charArray[idx];charArray[idx] = charArray[len - idx - 1];charArray[len - idx - 1] = temp;}return new String(charArray);}

从今天开始,每天在忙也要学习一下算法,巩固基础。日积月累。



0 0
原创粉丝点击