当前位置:网站首页>leetcode每日一练:将句子排序
leetcode每日一练:将句子排序
2022-07-27 02:50:00 【利刃Cc】
1859. 将句子排序
难度简单15
一个 句子 指的是一个序列的单词用单个空格连接起来,且开头和结尾没有任何空格。每个单词都只包含小写或大写英文字母。
我们可以给一个句子添加 从 1 开始的单词位置索引 ,并且将句子中所有单词 打乱顺序 。
- 比方说,句子
"This is a sentence"可以被打乱顺序得到"sentence4 a3 is2 This1"或者"is2 sentence4 This1 a3"。
给你一个 打乱顺序 的句子 s ,它包含的单词不超过 9 个,请你重新构造并得到原本顺序的句子。
示例 1:
输入:s = "is2 sentence4 This1 a3"
输出:"This is a sentence"
解释:将 s 中的单词按照初始位置排序,得到 "This1 is2 a3 sentence4" ,然后删除数字。
示例 2:
输入:s = "Myself2 Me1 I4 and3"
输出:"Me Myself and I"
解释:将 s 中的单词按照初始位置排序,得到 "Me1 Myself2 and3 I4" ,然后删除数字。
提示:
2 <= s.length <= 200s只包含小写和大写英文字母、空格以及从1到9的数字。s中单词数目为1到9个。s中的单词由单个空格分隔。s不包含任何前导或者后缀空格。
思路:
思路比较暴力哈哈,就是先定义一个变量 cur 查找数字的位置,然后用 begin 变量从 cur 的位置从后往前直到找到 空格,或者如果是第一个单词的话,会出界,所以要判断一下。接着将 begin 到 cur - 1 处的字母尾插到新的string变量 tmp 中,然后在末尾加上空格。
然后以此循环,每次给要找的数字加一,直到找不到该数字,cur 出界了为止。最后将末尾最后一个空格删掉。
class Solution {
public:
string sortSentence(string s) {
string tmp;
char i = '1'; //用于查看s中的数字字符
size_t cur = s.find(i); //用cur来找数字
while(cur != string::npos)
{
size_t begin = s.rfind(' ', cur); //用begin找该单词的开头
//若begin走到了开头,则直接将开头至cur的部分append即可
if(begin == string::npos)
{
tmp.append(s, 0, cur);
}
else
{
tmp.append(s, begin + 1, cur - begin - 1);
}
i++;
cur = s.find(i);
tmp.push_back(' '); //记得每次给tmp中尾插一个空格
}
tmp.pop_back(); //将最后的一个空格去掉
return tmp;
}
};
边栏推荐
- 什么是动画效果?什么是过渡效果?
- Golang sends email to the mail Library
- A. Parkway Walk
- [OBS] dynamic bit rate: bit rate estimation
- 2022年危险化学品经营单位主要负责人复训题库及答案
- Redis (IX) - redis distributed lock
- The job created by flinksqlclient will disappear after the restart of Flink. Is there any way?
- 分享当下人生——一个高中毕业生在中央电视台的六星期实习经历
- Share the current life -- a six week internship experience of a high school graduate in CCTV
- On the first day of Shenzhen furniture exhibition, the three highlights of Jin Ke'er booth were unlocked!
猜你喜欢
随机推荐
222. 完全二叉树的节点个数
03. Get the web page source code
jmeter接口测试(登录、注册)
三种常见的移动底盘运动学模型分析
Plato farm has a new way of playing, and the arbitrage eplato has secured super high returns
JMeter interface test (login, registration)
安装umi4阻碍一天的问题解决了
Message queue learning -- Concepts
04. Detailed steps for installing the simulated browser chromedriver in Google browser
零基础小白也能懂的 Redis 数据库,手把手教你易学易用!
真正意义上的数字零售应当具有更加丰富的内涵和意义
阿里云服务器域名加端口网页不能访问问题记录
Using redis C library, the problem of asynchronous memory leakage
Development of NFT digital collection system: Xiaoyi digital intelligence helps brands launch NFT with one click on the chain
Plato farm is expected to further expand its ecosystem through elephant swap
ApacheCon Asia 预热直播之孵化器主题全回顾
在Golang结构体中使用tag标签
The job created by flinksqlclient will disappear after the restart of Flink. Is there any way?
On the first day of Shenzhen furniture exhibition, the three highlights of Jin Ke'er booth were unlocked!
356页14万字高端商业办公综合楼弱电智能化系统2022版









