首页 > 代码库 > leetcode-344. Reverse String

leetcode-344. Reverse String

344. Reverse String

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

反转string字符串

java代码:

public class Solution {
    public String reverseString(String s) {
        String a="";
        StringBuilder sb=new StringBuilder(a);
        for(int i=0;i<s.length();i++){
            sb.insert(0,s.charAt(i));
        }
        return sb.toString();
    }
}

  第二种解法,更加快速

java代码:

public class Solution {
    public String reverseString(String s) {
        char[] ch=s.toCharArray();
        int i=0;
        int j=s.length()-1;
        char temp;
        while(i<j){
            temp=ch[i];
            ch[i++]=ch[j];
            ch[j--]=temp;
        }
        return new String(ch);
    }
}

  

leetcode-344. Reverse String