首页 > 其他分享 >leetcode 1592

leetcode 1592

时间:2023-03-20 19:11:06浏览次数:33  
标签:++ lo 1592 int hi cntWords text leetcode

注意整行输入的格式

#include<iostream>
#include<sstream>
using namespace std;
string reorderSpaces(string text) {
    string words[55];
    int n = text.size(),cntWords = 0, lo = 0, hi = 0,cntSpace = 0,avgSpace = 0,tailSpace = 0;
    while (lo < n) {
        while (lo < n && text[lo] == ' ') {
            cntSpace++;
            lo++;
        }
        hi = lo;
        while (hi < n && text[hi] != ' ') {
            hi++;
        }
        if (lo != hi) {
            words[cntWords++] = text.substr(lo, hi - lo);
        }
        lo = hi;
    }
    if (cntWords == 1) {
        text = words[0];
        for (int i = 0; i < cntSpace; i++) {
            text += " ";
        }
    }
    else {
        avgSpace = cntSpace / (cntWords-1);
        tailSpace = cntSpace % (cntWords-1);
        text = "";
        for (int i = 0; i < cntWords-1; i++) {
            text += words[i];
            for (int j = 0; j < avgSpace; j++) {
                text += " ";
            }
        }
        text += words[cntWords - 1];
        for (int i = 0; i < tailSpace; i++) {
            text += " ";
        }
    }
    return text;
}
int main() {
    string s;
    while (getline(cin,s) ){
        cout<<reorderSpaces(s)<<endl;
    }
    return 0;
}

 

标签:++,lo,1592,int,hi,cntWords,text,leetcode
From: https://www.cnblogs.com/stevenzrx/p/17237379.html

相关文章

  • #yyds干货盘点# LeetCode面试题:螺旋矩阵
    1.简述:给你一个m行n列的矩阵 matrix,请按照顺时针螺旋顺序,返回矩阵中的所有元素。 示例1:输入:matrix=[[1,2,3],[4,5,6],[7,8,9]]输出:[1,2,3,6,9,8,7,4,5]示例2:输......
  • Leetcode 4. 寻找两个正序数组的中位数(二分)
    题目链接在这里:是一道很好的二分题,一开始没有想到越界怎么处理,忽略了(m+n)/2一定介于min(n,m)和max(n,m)之间,因此如果确定在短的数组上进行二分就不用考虑越界问题了,其次......
  • leetcode刷题--TypeError:object of type 'NoneType' has no len()/AttributeError: 'N
    错误:一.TypeError:objectoftype'NoneType'hasnolen()list=[]i=0j=0whilelen(list)<=len(nums1)+len(nums2):报错:TypeError:objectoftype'NoneType'ha......
  • LeetCode 3.无重复字符的最长子串
    题目链接在这里:​​3.无重复字符的最长子串-力扣(LeetCode)​​这道题学习了几何函数set()的用法1classSolution(object):2deflengthOfLongestSubstring(self,s:......
  • LeetCode 2.两数相加
    题目链接在这里:​​2.两数相加-力扣(LeetCode)​​这道题学了一些python类和子函数的语法,发现语法与C++有异曲同工之妙1classListNode:2def__init__(self,val=0,......
  • Leetcode 1.两数之和(hash)
    题目链接在这里:​​1.两数之和-力扣(LeetCode)​​这道题主要学习了python中哈希表的使用,类似于c++中的map容器1#暴力2#classSolution:3#deftwoSum(self,nu......
  • 【LeetCode贪心#10】划分字母区间(有涉及hash数组的使用)
    划分字母区间力扣题目链接(opensnewwindow)字符串S由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串......
  • #yyds干货盘点# LeetCode面试题:最大子数组和
    1.简述:给你一个整数数组nums,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。子数组是数组中的一个连续部分。 示例1:输入:nums=[-2,1,-3,4,-......
  • #yyds干货盘点# LeetCode程序员面试金典:BiNode
    题目:二叉树数据结构TreeNode可用来表示单向链表(其中left置空,right为下一个链表节点)。实现一个方法,把二叉搜索树转换为单向链表,要求依然符合二叉搜索树的性质,转换操作应是原......
  • LeetCode435 -- 预定会议问题
    0.ref参考自1.题目描述预定会议问题:给定我们一堆区间,区间不能重叠(\([1,2]\)和\([2,3]\)的\(2\)不算重叠),求最多能保留多少个区间?做法:贪心,按【右端点】排序。......