反转单词

此博客链接:

反转单词

题目链接:https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/

题目

输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. ",则输出"student. a am I"。

示例 1:

输入: "the sky is blue"
输出: "blue is sky the"
示例 2:

输入: "  hello world!  "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3:

输入: "a good   example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

题解

先把字符串首尾的空格去掉,然后使用以空格分隔字符串,把字符串变成字符数组,从后向前遍历字符串 数组,把字符串拼接,这序员注意,split在以空格分隔字符串时,只能分割一个空格,如果有两个或者以上的空格时,那么空格也会被当成字符串保持在字符串数组中,在拼接字符串数组时,需要过滤空格。

这里需要注意l两点

1.字符串匹配使用equals匹配。

2.判断字符串是否等于空格时,使用""表示空格,中间不能加空格。

代码

class Solution {
    public String reverseWords(String s) {
        s=s.trim();
       String str[]=s.split(" ");
       
       int len=str.length;
       String res="";
       for(int i=len-1;i>0;i--){
           if(!str[i].equals("")){
              res+=str[i];
              res+=" ";
           }
             System.out.println(i);
             System.out.println(str[i]);
       
       }
          res+=str[0];
       return res;
    }
}

结果

出来混总是要还的
原文地址:https://www.cnblogs.com/ping2yingshi/p/14535167.html