美文网首页
反转字符串

反转字符串

作者: wangzaiplus | 来源:发表于2017-09-01 09:52 被阅读0次

package com.ctgu.test_Arithmetic;

import java.util.Stack;

public class ReverseString {

public static String reverse(String originStr) {
    if(originStr == null || originStr.length() <= 1) 
        return originStr;
    return reverse(originStr.substring(1)) + originStr.charAt(0);
}

public static String reverse2(String originStr) {
    if(originStr == null || originStr.length() <= 1) 
        return originStr;
    StringBuffer sb = new StringBuffer();
    for(int i=originStr.length()-1; i>=0; i--){
        sb.append(originStr.charAt(i));
    }
    return sb.toString();
}

public static void reverse3(String originStr) {
    Stack<Character> stack = new Stack<Character>();
    for(int i=0; i<originStr.length(); i++){
        stack.push(originStr.charAt(i));
    }
    while(!stack.isEmpty()){
        System.out.print(stack.pop());
    }
}

public static void main(String[] args) {
    System.out.println(reverse("abcdefg"));
    System.out.println(reverse2("abcdefg"));
    reverse3("abcdefg");
}

}
运行结果:
gfedcba
gfedcba
gfedcba

相关文章

网友评论

      本文标题:反转字符串

      本文链接:https://www.haomeiwen.com/subject/gfzahxtx.html