---
title: "java 实现字符串逆置"
author: "简单的茶"
date: "2014-03-17T10:35:35Z"
tags: []
categories: ["互联网"]
slug: "java"
draft: false
lastmod: "2014-03-17T10:35:35Z"
id: 2031874
url: "https://lisai.iteye.com/blog/2031874"
---

题目：
    写一个函数，将一个字符串变成倒序，结果存于原字符串，不得额外分配空间保存字符串。例如：abcdef 经变换后为 fedcba

算法思路：
     采用递归算法，字符两两交换。

package reverseString;

public class ReverseString
{
	
	/**
	 * @param args
	 */
	public static void main(String args)
	{
		String test = "12345";
		System.out.println(reverse(test, 0, (test.length() - 1)));
	}
	
	private static String reverse(String string, int startIndex, int endIndex)
	{
		if (startIndex >= endIndex)
			return string;
		
		// swap char at startIndex and endIndex
		char characterAtEnd = string.charAt(endIndex);
		
		if ((endIndex + 1) < string.length())
		   string = string.substring(0, endIndex) + 
				string.charAt(startIndex) + 
				string.substring(endIndex + 1, string.length());
		else 
			string = string.substring(0, endIndex) + string.charAt(startIndex);
		
			
		  string = string.substring(0, startIndex) + 
		      characterAtEnd + 
		      string.substring(startIndex + 1, string.length());
	
		
		  return reverse(string, ++startIndex, --endIndex);		
	}
	
}