首页 > 试题广场 >

字符串倒序

[编程题]字符串倒序
  • 热度指数:4115 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
薯队长带着小红薯参加密室逃脱团建游戏,首先遇到了反转游戏,小红薯们根据游戏提示收集了多个单词线索,并将单词按要求加一个空格组 成了句子,最终要求把句子按单词反转解密。 说明:收集的时候单词前后可能会有多个空格,反转后单词不能有多个空格,具体见输入输出样例。

输入描述:
输入一个字符串。包含空格和可见字符。长度<=100000。 


输出描述:
输出一个字符串,表示反转后结果。
示例1

输入

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;
}

发表于 2020-11-29 14:06:33 回复(0)
通过了所有测试案例:
  1.     不知道为什么直接用if判断空格删不干净,最后只能用编码判断空格了
  2.     核心语句:
  !Number.isNaN(   item.charCodeAt(0)   )   end.unshift(item);
  3.    关于charCodeAt(0):
  • 自己输入的空格,返回结果是32,console.log('space::   ',' '.charCodeAt(0))  //32
  • 命令行输入的空格,返回结果是NaN,故非NaN的添加到数组头中
  • 为什么不直接:返回结果是NaN,则splice(index,1)删除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(' '));
})





编辑于 2020-11-08 08:32:02 回复(0)
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%,自己编译器全通过

发表于 2020-10-19 14:01:31 回复(0)
#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]);
}

编辑于 2020-10-14 19:17:07 回复(0)
怎样才能通过呢😐直接写函数不能过编译诶
发表于 2020-06-20 12:05:58 回复(3)
function reverseStr (str) {
    var s = str.match(/[^\s]+/g)
    s = s.reverse()
    return s.join(' ')
}
发表于 2020-06-12 13:46:09 回复(2)
words = input().split()[::-1]
print(" ".join(words))


发表于 2020-07-04 12:19:05 回复(4)
✭头像
import sys
s = [i for i in sys.stdin.readline().split()]
for i in range(len(s)-1, -1, -1):
    print(s[i], end=' ')

发表于 2020-06-13 12:25:21 回复(0)
import java.util.*;
public class Main{
public static void main(String[] args)
{
    Scanner in=new Scanner(System.in);
    String str=in.nextLine();
    List<String> words=Arrays.asList(str.split("\\s+"));
    Collections.reverse(words);
    String res=String.join(" ", words);
    System.out.print(res);
}
}

发表于 2020-06-29 19:46:04 回复(0)
#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;
}

编辑于 2020-09-15 11:24:02 回复(0)
#include <bits/stdc++.h>
using namespace std;
stack<string> s;
  
int main(int argc, char**argv) {
    string str;
    while(cin >> str) {
        s.push(str);
    }
    while(s.size())
    {
        string res = s.top();
        s.pop();
        cout << res << " ";
    }
   
      
    return 0;
}

发表于 2020-08-11 13:04:32 回复(0)
constrl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
constreadline = async () => (await iter.next()).value;
 
voidasync function () {
    // Write your code here
    while(line = await readline()){
        constres = line.split(" ").filter(item => item !== "").reverse()
        console.log(res.join(" "))
    }
}()
发表于 2023-11-24 23:07:40 回复(0)
直接一行 全通过
while(line = await readline()){
         console.log(line.trim().replace(/\s+/g,' ').split(' ').reverse().join(' '))
    }
发表于 2023-05-12 15:40:38 回复(0)
代码c++
思路:vector直接解决
#include <bits/stdc++.h>
using namespace std;

int main() {
    string ss;
    vector<string> s;
    while(cin>>ss){
        s.emplace_back(ss);
    }
    for(auto i=s.rbegin();i!=s.rend();i++){
        cout<<*i;
        if(i!=s.rend()-1)
        cout<<" ";
    }
    }
发表于 2023-04-14 23:54:10 回复(0)
word = list(input().split())  #以空格为分隔符将字符串转换成列表,一个单词即为一个元素
word = word[::-1]  #列表翻转
word = ' '.join(word)  #翻转后的列表用空格连接转换成字符串
print(word)

编辑于 2023-04-09 10:48:47 回复(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();
});


发表于 2023-03-30 23:52:53 回复(0)
// JS Node
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void async function () {
    // Write your code here
    while(line = await readline()){
        let str = line.replace(/\s+/g," ").split(" ").reverse().join(" ");
        console.log(str);
    }
}()

发表于 2023-03-26 08:56:55 回复(0)

因为输入的字符串会有空格键和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(' ');
}
发表于 2023-03-25 21:00:39 回复(0)
方法:用split方法可直接筛掉空格,然后逆序输出list中所有元素
import sys

for line in sys.stdin:
    a = line.split()[::-1]
    for i in a:
        print(i, end=' ')
发表于 2023-03-25 19:30:36 回复(0)
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s[] = sc.nextLine().split("\\s+");
        ArrayList<String> res = new ArrayList<>();
        for (int i = s.length-1; i>=0;i--) {
            res.add(s[i]);
        }
        System.out.println(String.join(" ",res));
    }
}
以空格分割一行字符串,再反转,最后加上空格输出
发表于 2022-09-18 22:00:23 回复(0)