LeetCode随缘刷题之截断句子

这道题相对比较简单。正好最近学到StringBuilder就用了。

package leetcode.day_12_06;

/**
 * 句子 是一个单词列表,列表中的单词之间用单个空格隔开,且不存在前导或尾随空格。每个单词仅由大小写英文字母组成(不含标点符号)。
 * <p>
 * 例如,"Hello World"、"HELLO" 和 "hello world hello world" 都是句子。
 * 给你一个句子 s 和一个整数 k,请你将 s 截断 ,使截断后的句子仅含 前 k 个单词。返回 截断 s 后得到的句子。
 * <p>
 * 示例 1:
 * <p>
 * 输入:s = "Hello how are you Contestant", k = 4
 * 输出:"Hello how are you"
 * 解释:
 * s 中的单词为 ["Hello", "how" "are", "you", "Contestant"]
 * 前 4 个单词为 ["Hello", "how", "are", "you"]
 * 因此,应当返回 "Hello how are you"
 * 示例 2:
 * <p>
 * 输入:s = "What is the solution to this problem", k = 4
 * 输出:"What is the solution"
 * 解释:
 * s 中的单词为 ["What", "is" "the", "solution", "to", "this", "problem"]
 * 前 4 个单词为 ["What", "is", "the", "solution"]
 * 因此,应当返回 "What is the solution"
 * 示例 3:
 * <p>
 * 输入:s = "chopper is not a tanuki", k = 5
 * 输出:"chopper is not a tanuki"
 *
 * @author soberw
 * @Classname TruncateSentence1816
 * @Description
 * @Date 2021-12-06 10:33
 */
public class TruncateSentence1816 {
    /**
     * @param s 一个单词列表
     * @param k 想要截取的单词个数
     * @description: 将 s 截断 ,使截断后的句子仅含 前 k 个单词。
     * @return: 返回 截断 s 后得到的句子
     * @author: soberw
     * @time: 2021/12/6 10:34
     */
    public String truncateSentence(String s, int k) {
        String[] str = s.split(" ");
        StringBuilder sbu = new StringBuilder();
        for (int i = 0; i < k; i++) {
            sbu.append(str[i]);
            sbu.append(" ");
        }
        return sbu.toString().trim();
    }

    public static void main(String[] args) {
        String s= "What is the solution to this problem";
        System.out.println(new TruncateSentence1816().truncateSentence(s,4));
    }
}

运行结果:
在这里插入图片描述
在这里插入图片描述

posted @ 2022-02-09 19:45  soberw-  阅读(39)  评论(0)    收藏  举报