Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1816. 截断句子 #143

Open
yankewei opened this issue Dec 6, 2021 · 1 comment
Open

1816. 截断句子 #143

yankewei opened this issue Dec 6, 2021 · 1 comment
Labels
字符串 题目类型为字符串 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

yankewei commented Dec 6, 2021

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

例如,"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 中的单词之间由单个空格隔开
  • 不存在前导或尾随空格

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/truncate-sentence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

@yankewei yankewei added 字符串 题目类型为字符串 简单 题目难度为简单 labels Dec 6, 2021
@yankewei
Copy link
Owner Author

yankewei commented Dec 6, 2021

遍历

没什么说的,很很简单

func truncateSentence(s string, k int) string {
    ret := s
    spaceCount := 0
    for i := 0; i < len(s); i++ {
        if s[i] == ' ' {
            spaceCount++
        }
        if spaceCount == k-1 {
            ret = s[0:i+1]
        }
    }
    return ret
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
字符串 题目类型为字符串 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant