侧边栏壁纸
博主头像
GabrielxD

列車は必ず次の駅へ。では舞台は?私たちは?

  • 累计撰写 674 篇文章
  • 累计创建 128 个标签
  • 累计收到 20 条评论

目 录CONTENT

文章目录

【模拟】截断句子

GabrielxD
2022-05-17 / 0 评论 / 0 点赞 / 120 阅读 / 431 字
温馨提示:
本文最后更新于 2022-07-26,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

题目

1816. 截断句子


句子 是一个单词列表,列表中的单词之间用单个空格隔开,且不存在前导或尾随空格。每个单词仅由大小写英文字母组成(不含标点符号)。

  • 例如,"Hello World""HELLO""hello world hello world" 都是句子。

给你一个句子 s 和一个整数 k ,请你将 s 截断 ,使截断后的句子仅含 前 k 个单词。返回 截断 s 后得到的句子。

示例 1:

输入: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:

输入: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:

输入:s = "chopper is not a tanuki", k = 5
输出:"chopper is not a tanuki"

提示:

  • 1 <= s.length <= 500
  • k 的取值范围是 [1, s 中单词的数目]
  • s 仅由大小写英文字母和空格组成
  • s 中的单词之间由单个空格隔开
  • 不存在前导或尾随空格

解题

方法一:模拟

思路

根据题意模拟,有手就行。

代码

class Solution {
    public String truncateSentence(String s, int k) {
        String[] strArr = s.split(" ");
        StringBuilder ans = new StringBuilder();
        for (int i = 0; i < k; i++) ans.append(strArr[i]).append(" ");
        return ans.deleteCharAt(ans.length() - 1).toString();
    }
}

优化

class Solution {
    public String truncateSentence(String s, int k) {
        int bound = 0;
        for (; k > 0; k--) {
            bound = s.indexOf(' ', bound + 1);
        }
        return bound == -1 ? s : s.substring(0, bound);
    }
}
0

评论区