您的位置:首页 > 其它

LeetCode_001:Reverse Words in a String

2014-07-10 20:44 204 查看
package com.abuge;
/**
* 需求:
* 输入一个字符串,将其反转。
* 例:
* s = "the sky is blue"
* return "blue is sky the"
* 方法&步骤:
* 1、 将字符串首尾空格去除
* 2、利用正则表达式,将字符串转换成字符串数组
* 3、反转字符串数组
* @author AbuGe
*
*/
public class Solution
{
public static String reverseWords(String s)
{
String strTmp = s.trim();
String[] strArray = strTmp.split(" +");
//反转数组
int len = strArray.length;
int startIndex = 0;
int endIndex = len - 1;
while(startIndex < endIndex)
{
String tmp = strArray[startIndex];
strArray[startIndex] = strArray[endIndex];
strArray[endIndex] = tmp;
startIndex++;
endIndex--;
}
//定义一个字符串缓冲区
StringBuffer sb = new StringBuffer();
for(int i = 0; i < len; i++)
{
sb.append(strArray[i]);
if(i != len - 1)
sb.append(" ");
}
return sb.toString();
}

public static void main(String[] args)
{
String str = "        the   sky      is blue ";
String out = reverseWords(str);
System.out.println(out);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: