13、反转字符串III

2018-11-07  本文已影响11人  ZeroForSpider

1、题目大意:

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

示例 1:

输入: "Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc"
注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。

2、解题思路

该题目的输入为一个以单一空格分隔的单词字符串序列。要求输出每个单词反序构成的字符串序列。该题目还算比较简单。因为是单一空格连接的字符序列,所以可以采用字符串的分隔方法。将每个单词分隔出来,然后反序放入新序列即可。

3、代码如下:

class Solution {
    public String reverseWords(String s) {
       int length=s.length();
       char [] newChars=new char[length];
       int n=0;
       String [] oldChars=s.split(" ");
       for(int i=0;i<oldChars.length;i++){
           char [] tempChars=oldChars[i].toCharArray();
           for(int j=tempChars.length-1;j>=0;j--){
               newChars[n++]=tempChars[j];
           }
           if(n!=length){
            newChars[n++]=' ';  //最后没有空格
           }
       }
        return String.valueOf(newChars);
    }
}

public class MainClass {
    public static String stringToString(String input) {
        if (input == null) {
            return "null";
        }
        return Json.value(input).toString();
    }
    
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = in.readLine()) != null) {
            String s = stringToString(line);
            
            String ret = new Solution().reverseWords(s);
            
            String out = (ret);
            
            System.out.print(out);
        }
    }
}

4、运行结果

image.png
上一篇 下一篇

猜你喜欢

热点阅读