你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

Leetcode--Java--1816. 截断句子

2021/12/6 9:12:34

题目描述

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

例如,“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"

思路

方法一:split()大法
方法二:模拟 对空格计数

  1. 设置一个cnt表示截取出的数,碰到空格就计数一次,前面肯定是单词。当cnt==k就不用再拼接空格。

代码

方法一:

class Solution {
    public String truncateSentence(String s, int k) {
      String words[] = s.split(" ");
      StringBuffer res = new StringBuffer();
      for (int i = 0; i < k; i ++ ) {
          res.append(words[i]);
          if (i < k - 1)
          res.append(" ");
      }
      return res.toString();
    }
}

方法二:

class Solution {
    public String truncateSentence(String s, int k) {
     StringBuffer res = new StringBuffer();
     int cnt = 0;
     int n = s.length();
     for (int i = 0; i < n && cnt < k; i ++ ) {
         char c = s.charAt(i);
         //碰到空格就计数
         if (c == ' ') cnt ++;
         //只要不等于k就拼接  间接处理了空格分隔问题
         if (cnt < k) res.append(c);
     }
     return res.toString();
    }
}