求职面试(字符串反转,单词反转)


本篇博客包括常见的字符串反转算法。其中包括四个字符串反转算法。还有一个对单词的反转(比如:输入 how are you!  输出 you! are how)


希望对广大朋友有帮助!


package com.robin.stringAndSZ;

import java.util.Stack;

public class ReverseString {

	//Method one:
	public static String reverseString1(String srcString){
		if(srcString.length() != 0){
			return null;
		}
		
		return reverseString1(srcString.substring(1))+srcString.charAt(0);
	}
	
	//Method two:
	public static String reverseString2(String srcString){
		
		StringBuffer sb = new StringBuffer();
		for(int i = srcString.length()-1; i >= 0; i--){
			sb.append(srcString.charAt(i));
		}
		return new String(sb);
	}
	
	//Method three:
	public static String reverseString3(String srcString){
		String desString = new String();
		Stack<Character> stack = new Stack<Character>();
		for(int i = 0; i < srcString.length();i++){
			stack.push(srcString.charAt(i));
		}
		
		for(int i = 0; i < srcString.length();i++){
			desString += stack.pop();
		}
		return desString;
	}
	
	//Method four:
	public static void swap(char[] src,int start,int end){
		while(start < end){
			char temp = src[start];
			src[start] = src[end];
			src[end] = temp;
			
			start++;
			end--;
		}
		
		//return new String(src);
	}
	
	public String reverseString4(String str){
		char[] src = str.toCharArray();
		swap(src,0,str.length()-1);
		String result = new String(src);
		//System.out.println(result);
		return result;
	}
	
	
	public static void swapWord(String str){
		
		char[] src = str.toCharArray();
		swap(src,0,str.length()-1);
		
		int begin = 0;
		for(int i = 1 ; i < src.length; i++){
			if(src[i] == ' '){
				swap(src,begin,i-1);
				begin = i+1;
			}
		}
		swap(src,begin,src.length-1);
		System.out.println(new String(src));
		
		
	}
	
 	public static void main(String[] args) {

 		System.out.println(reverseString1("hello!"));
 		System.out.println(reverseString2("hello!"));
 		System.out.println(reverseString3("hello!"));
 		//System.out.println(reverseString4("hello!"));
 		
 		//System.out.println(swapWord("how are you!"));
 		swapWord("how are you!");
	}

}

你可能感兴趣的:(java,字符串,面试题,单词反转)