114.Reverse String

来源:互联网 发布:数据字典下载 编辑:程序博客网 时间:2024/06/02 05:31

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

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

分析:

   首先把字符串转化为字符数组,然后转置字符数组,然后再转化为字符串。不直接交换字符串是因为字符串是不可变的,每次改变字符串则会生成一个新的自字符串对象,影响性能。

 /**@author  * 给定一个字符串对其进行逆转。 * @date 20160423 * @param s * @return */public String reverseString(String s) {char[] arr = s.toCharArray();int  len = s.length();if(len<=1){return s;}char temp;for(int i=0;i<len/2;i++){temp = arr[i];arr[i] = arr[len-i-1];arr[len-i-1] = temp;}    return new String(arr);            }

0 0
原创粉丝点击