`
oywl2008
  • 浏览: 1000923 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

逆转字符串 Write a String Reverser (and use Recursion!)

 
阅读更多

 

public class Reverse {

	public static String ReverseStr(String str){
		
		if(str==null&&str.length()<=1){
			return str;
		}else{
			return new StringBuffer(str).reverse().toString();
		}
		
	}
	
	public static String ReverseStr1(String str){
		 if ((null == str) || (str.length()  <= 1)) {
			 return str;
         }
		 return ReverseStr1(str.substring(1)) + str.charAt(0);
	}
	
	public static String ReverseStr2(String str){
		 if ((null == str) || (str.length()  <= 1)) {
             return str;
         }else{
        	 String temp = "";
        	 char charArray[]=str.toCharArray();
        	 for(int i=charArray.length-1;i>=0;i-- ){
        		 temp += charArray[i];
        	 }
        	 return temp;
         }
         
	}
	
	
	
	public static void main(String[] args) {
		System.out.println(ReverseStr("oywl"));
		System.out.println(ReverseStr1("oywl"));
		System.out.println(ReverseStr2("oywl"));
	}

}

 

 

 

http://codemonkeyism.com/java-interview-questions-write-a-string-reverser-and-use-recursion/

 

 

分享到:
评论
2 楼 zhaojiafan 2012-07-22  
return ReverseStr1(str.substring(1)) + str.charAt(0);
这就话是什么意思了。和charAt相加是????
1 楼 zhaojiafan 2012-07-22  
public class StringUtils {
	
	public static String reverse(String str){
		if(str==null || "".equals(str.trim())){
			return str;
		}
		return new StringBuffer(str).reverse().toString();
	}
	
	public static String reveree2(String str){
		if(str==null || "".equals(str.trim())){
			return str;
		}
		char[] ch = str.toCharArray();
		StringBuilder sb = new StringBuilder();
		for(int i= ch.length-1; i>=0; i--){
			sb.append(ch[i]);
		}
		return sb.toString();
	}
	
	public static void main(String[] args) {
		System.out.println(StringUtils.reverse("abc中国"));
		System.out.println(StringUtils.reveree2("abc中国"));
	}
}

自己也写了个

相关推荐

Global site tag (gtag.js) - Google Analytics