LeetCode557. 反转字符串中的单词 III

给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

示例 1:

输入: "Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc" 

注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。



思路:将字符串分割成不含空字符的单个字符串数组,将数组中的每个字符串反转,最后将数组中的字符串拼凑成一个字符串。

class Solution {
    public String reverseWords(String s) {
        if(s==null) {
    		return null;
    	}
        String words[]=s.split(" ");
        String newS="";
        for(String str:words) {
        	String temp=reverseString(str);
        	newS=newS+" "+temp;
        //	System.out.println(temp);
        }
    	return newS.trim();//忽略字符串的前导空白和尾部空白
    }
     //反转字符串
    public static String reverseString(String s) {
        if(s==null) {
	    	return null;
	    }
	    int len=s.length();
		char[] ch=new char[len];
		int i,j;
		for(i=0,j=len-1;i<len;i++,j--) {
			ch[i]=s.charAt(j);
		}
		String str=new String(ch);
		return str;
   }
}

猜你喜欢

转载自blog.csdn.net/weixin_40550726/article/details/80593149
今日推荐