标签:string
Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". Update (2015-02-12): For C programmers: Try to solve it in-place in O(1) space.
题意:反转字符串中的单词,注意空格的处理!!!
public class Solution { public String reverseWords(String s) { int length=s.length(); // char[] ch=s.toCharArray(); if(s==null || length==0)return s; int end=length; StringBuilder ret=new StringBuilder(); for(int i=length-1;i>=0;i--){ if(s.charAt(i)==‘ ‘)end=i; else if(i==0 || s.charAt(i-1)==‘ ‘){ //如果里面有单词,新加单词时先加空格 if(ret.length()!=0) ret.append(‘ ‘); ret.append(s.substring(i,end)); } } return ret.toString(); } }
PS:群里大神思路。挺简洁的。从后往前遍历。找到单词就添加到ret,
Leetcode 448. Find All Numbers Disappeared in an Array JAVA语言151. Reverse Words in a String
标签:string
原文地址:http://fulin0532.blog.51cto.com/6233825/1902701