题目描述:
Write a function that takes a string as input and returns the string reversed.
思路:
逆序输出一个字符串
第一种方法:
从尾到头遍历原字符串,返回到result中。但提交提示超时了,给了一个巨长无比的测试用例。
第二种方法,从0-s.length()/2,依次交换头和尾的字符 时间复杂度减半
注意。将string转为char 用charAt()将String中某一位转为char.或者s.toCharArray()可以将整个string转为char
char转string则使用new String(ch)方法
第三种方法,使用栈。后进先出
将s入栈,然后出栈存入result
但还是 Time Limit Exceeded
public class Solution344 { public String reverseString(String s) { //方法1,遍历。超时 /*String result = ""; for(int i = s.length()-1; i >=0;i--){ result += s.charAt(i); } return result;*/ //方法2,从0-s.length()/2,依次交换头和尾的字符 时间复杂度减半 /*int i=0,j=s.length()-1; char ch[] = s.toCharArray(); char temp; while(i<s.length()/2){ temp = s.charAt(i); ch[i] = ch[j]; ch[j] = temp; i++; j--; } return new String(ch);*/ Stack<Character> stack = new Stack<>(); int i = 0; String result = ""; while(i < s.length()){ stack.push(s.charAt(i)); i++; } while(!stack.isEmpty()){ result+=stack.pop(); } return result; } public static void main(String[] args) { // TODO Auto-generated method stub Solution344 solution344 = new Solution344(); String s = "hello"; System.out.println(solution344.reverseString(s)); } }