0
点赞
收藏
分享

微信扫一扫

Leetcode-1859: 将句子排序

链接

力扣icon-default.png?t=M0H8https://leetcode-cn.com/problems/sorting-the-sentence/

题目

示例

提示

  • 2 <= s.length <= 200
  • s 只包含小写和大写英文字母、空格以及从 1 到 9 的数字。
  • s 中单词数目为 1 到 9 个。
  • s 中的单词由单个空格分隔。
  • s 不包含任何前导或者后缀空格。

思路

由于题目说了最多只有9个单词,因此可以定义一个长度为9的字符串数组,遍历字符串,分别将数字和字母取出,遇到字母则一直添加到临时字符串中(相当于取出单词),遇到数字便将前面取出的单词存到字符串数组的对应位置,并清空临时字符串,最后遍历字符串数组逐个取出单词拼成句子即可。

C++ Code

class Solution {
public:
    string sortSentence(string s) {
        vector<string> words(9); //根据题意,最多有9个单词,用一个字符串数组存储
        string word=""; //用于临时存放每个单词
        int n=0; //统计单词个数

        for(char x:s)
        {
            if('1'<=x&&x<='9') //数字
            {
                words[x-'1']=word;
                n++;
                word=""; //清空字符串
            }
            else if(x!=' ')
            {
                word+=x;
            }
        }
        string result=words[0];
        for(int i=1;i<n;i++) result+=" "+words[i];
        return result;
    }
};
举报

相关推荐

0 条评论