牛客题解 | 多组_带空格的字符串_T组形式

题目

题目链接

解题思路

特别地,对于C++,需要使用 getline(cin,s) 而非 cin>>s 的方式读入带空格的字符串。


代码

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main(void)
{
  ios::sync_with_stdio(false);
  cin.tie(0);
  string s,tmp,ans;
  int t,n;
  cin>>t>>ws;
  while(t--)
  {
    cin>>n>>ws; // ws 用于去除多余的控制符(\r 和 \n)
    getline(cin,s);
    ans=tmp="";
    for(auto &e:s)
    {
      if(e==' ')
      {
        if(!tmp.empty())
        {
          ans+=tmp;
          tmp.clear();
        }
      }
      else
        tmp+=e;
    }
    ans+=tmp;
    reverse(ans.begin(),ans.end());
    cout<<ans<<'\n';
  }
  return 0;
}
import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        String s;
        int t,n;
        s=sc.nextLine();
        t=Integer.parseInt(s);
        while(t-->0){
            s=sc.nextLine();
            n=Integer.parseInt(s);
            s=sc.nextLine();
            String[] a=s.split(" ");
            String b=String.join("",a);
            b=new StringBuilder(b).reverse().toString();
            System.out.println(b);
        }
    }
}
t=int(input())
for _ in range(0,t):
    n=int(input())
    s=input()
    a=list(map(str,s.split()))
    s=''.join(a)
    s=s[::-1]
    print(s)

算法及复杂度

  • 算法:枚举。
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)

这个是牛客输入输出题单题解,欢迎大家刷牛客题库。这个是牛客输入输出题单题解,欢迎大家刷牛客题库。这个是牛客输入输出题单题解,欢迎大家刷牛客题库。这个是牛客输入输出题单题解,欢迎大家刷牛客题库。这个是牛客输入输出题单题解,欢迎大家刷牛客题库。

posted @   wangxiaoxiao  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示