zoukankan      html  css  js  c++  java
  • 每日一练leetcode

    反转单词顺序

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

     解法一双指针

    倒叙遍历字符串s,记录单词左右索引边界i,j

    每确定一个单词边界。就将其添加至索引列表res

    最终,将单词列表拼接为字符串,应返回即可

    算法好理解 重点解释一下如何实现

    class Solution {
        public String reverseWords(String s) {
            s = s.trim(); // 删除首尾空格
            int j = s.length() - 1, i = j;
            StringBuilder res = new StringBuilder();
            while(i >= 0) {
                while(i >= 0 && s.charAt(i) != ' ') i--; // 搜索首个空格
                res.append(s.substring(i + 1, j + 1) + " "); // 添加单词
                while(i >= 0 && s.charAt(i) == ' ') i--; // 跳过单词间空格
                j = i; // j 指向下个单词的尾字符
            }
            return res.toString().trim(); // 转化为字符串并返回
        }
    }
    

      1)删除首尾空格函数string s.trim

      2)遍历字符串中的单个字符string s.charAt()

      3)将StringBuilder类型转化为String类型 toString()

  • 相关阅读:
    Netty 超时机制及心跳程序实现
    ZJUTACM
    寻找素数对
    HDU 1021 Fibonacci Again
    HDU 1019 Least Common Multiple
    HDU 1017 A Mathematical Curiosity
    HDU 1014 Uniform Generator
    HDU 1013 Digital Roots
    HDU 1008 Elevator
    Educational Codeforces Round 2 B. Queries about less or equal elements
  • 原文地址:https://www.cnblogs.com/nenu/p/15233513.html
Copyright © 2011-2022 走看看