输入一个字符串。包含空格和可见字符。长度<=100000。
输出一个字符串,表示反转后结果。
the sky is blue!
blue! is sky the
输出一个字符串,表示反转后结果。
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main(){
//the sky is blue!
//!eulb si yks eht
string t, dst, src;
while(cin >> t){
src += t;
src += ' ';
}
src = src.substr(0, src.length() - 1); //丢掉最后一个空格
reverse(src.begin(), src.end());
int pos1 = 0; //第一次出现空格的位置
int pos2 = 0; //第一次出现字符的位置
while((pos1 = src.find_first_of(' ')) != string::npos){
pos2 = src.find_first_not_of(' ');
string temp = src.substr(pos2, pos1); //截取一个单词
reverse(temp.begin(), temp.end()); //翻转
temp += ' '; //加上空格
dst += temp; //赋值到目标字符串
src = src.substr(pos1 + 1); //更新src
}
//找不到空格了, 说明已经到了最后一个单词了
reverse(src.begin(), src.end());
dst += src;
cout << dst << endl;
return 0;
} !Number.isNaN( item.charCodeAt(0) ) end.unshift(item);
const readline=require('readline');
const rl=readline.createInterface({
input:process.stdin,
output:process.stdout
});
rl.on('line',(line)=>{
let arr=line.split(' '),brr=[];
arr.forEach((item,index)=>{
if( !Number.isNaN(item.charCodeAt(0))){//非NaN的添加到数组头中
brr.unshift(item);
}
})
console.log(brr.join(' '));
}) while(str=readline()){
str = str.replace(/\s+/g," ").split(" ")
var arr=[];
var len=str.length;
for(var i=0;i<len;i++){
arr[i]=str.pop()
}
print(arr.join(' '))
}
牛客通过90%,自己编译器全通过
#include<stdio.h>
#include<string.h>
int main()
{
char a[100000];
char b[100000];
int counter=0;
gets(a);
for(int i=0;i<strlen(a);i++)//去掉多余的空格并存放在新数组b中
{
if(a[i]!=32)
{
b[counter]=a[i];
counter++;
}
if(a[i]==32&&a[i+1]!=32)
{
b[counter]=a[i];
counter++;
}
}
int counter2=counter;
for(int i=counter-1;i>=0;i--)//逆序遍历,打印空格后单词
{
if(b[i]==32)
{
for(int j=i+1;j<counter2;j++)
printf("%c",b[j]);
counter2=i;
printf(" ");
}
}
for(int j=0;j<counter2;j++)//打印第一个单词
printf("%c",b[j]);
}
#include <iostream>
#include <string>
using namespace std;
int main(){
string str;
getline(cin,str);
string ans="";
int n=str.size();
int i=n-1,j=n-1;
while(j>=0){
if(str[j] != ' '){
for(i=j;i>=0;i--){
if(str[i] == ' ')
break;
}
ans+=str.substr(i+1,j-i);
ans+=" ";
j=i;
}
j--;
}
ans.erase(ans.end()-1);
cout<<ans<<endl;
return 0;
}
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.on("line", (line) => {
// 双指针
const str = line.replace(/\s+/g, " ").trim();
let i = 0;
let j = 0;
const words: string[] = [];
while (j < str.length) {
if (str[j] !== " ") {
j++;
} else {
words.unshift(str.substring(i, j));
while (j < str.length && str[j] === " ") {
j++;
}
i = j;
}
}
words.unshift(str.substring(i, j));
console.log(words.join(" "));
rl.close();
}); 因为输入的字符串会有空格键和tab键,所以投机取巧通过了~
function reverseStr(str){
let random = Math.random();
let arr = str.replaceAll(' ', random).replaceAll('\t',random).split(random);
return arr.filter(item => item !== '').reverse().join(' ');
}