首页 > 试题广场 >

单词倒排

[编程题]单词倒排
  • 热度指数:391422 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
\hspace{15pt}对于给定的若干个单词组成的句子,每个单词均由大小写字母构成,单词间使用非字母字符分隔。输出以单词为单位逆序排放的结果,即仅逆序单词间的相对顺序,不改变单词内部的字母顺序。
\hspace{15pt}特别地,在输出结果中,去除原有的分隔符,转而使用单个空格间隔单词。

输入描述:
\hspace{15pt}在一行上输入若干个字符串,每个字符串长度为 1 \leqq {\rm length}(s) \leqq 20 ,仅由大小写字母构成,代表一个单词。单词间还夹杂了一定数量的非字母字符(但保证是可见字符),代表分隔符。

\hspace{15pt}除此之外,保证总字符长度不超过 10^4


输出描述:
\hspace{15pt}在一行上输出一个句子,代表以单词为单位逆序排放的结果。单词间使用单个空格分隔。
示例1

输入

Nowcoder Hello

输出

Hello Nowcoder
示例2

输入

$bo*y gi!r#l

输出

l r gi y bo
import java.util.*;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        StringBuilder builder = new StringBuilder(str);
        for (int i = 0; i < builder.length(); i++) {
            if (!Character.isLetterOrDigit(str.charAt(i))) {
                builder.setCharAt(i, ' ');
            }
        }
        String str1 = builder.toString();
        String[] str2 = str1.split(" ");


        StringBuilder builder2 = new StringBuilder();
        for (int i = str2.length - 1; i >= 0; i--) {
            builder2.append(str2[i] + " ");
        }
        String result = builder2.toString();
        System.out.println(result);
    }
}


发表于 2025-05-19 22:53:35 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String str = in.nextLine();
            String[] arr = str.split("[^a-zA-Z]");
            for (int i = arr.length - 1; i >= 0; i--) {
                System.out.print(arr[i] + " ");
            }
        }
    }
}
发表于 2025-03-26 13:43:17 回复(0)
import java.util.Scanner;
import java.util.regex.Pattern;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str1 = sc.nextLine();
        char[] chars = str1.toCharArray();
        Pattern p = Pattern.compile("[a-zA-Z]");
        for (int i = 0; i < chars.length; i++) {
            if(!p.matcher(String.valueOf(chars[i])).matches()){
                chars[i] = ' ';
            }
        }

        String s = String.valueOf(chars);
        if(!p.matcher(s.substring(0,1)).matches()){
            s = s.substring(1);
        }

        String[] s1 = s.split(" ");
        StringBuilder result = new StringBuilder();
        for (int i = s1.length-1; i >=0; i--) {
            if(i!=0){
                result.append(s1[i]).append(" ");
            }else {
                result.append(s1[i]);
            }

        }

        System.out.println(result.toString());
    }
}
发表于 2025-03-26 10:33:44 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine(); // 原字符串
        String res = ""; // 结果字符串

        // 方法1
        // for (int i = 0; i < s.length(); i++) {
        //     String t = "";
        //     while (i < s.length() && !Character.isLetter(s.charAt(i))) {
        //         i++;
        //     }
        //     while (i < s.length() && Character.isLetter(s.charAt(i))) {
        //         t += s.charAt(i);
        //         i++;
        //     }
        //     res = t + " " + res;
        // }
        // System.out.print(res);

        // 方法2
        // 利用正则 剔除其他字符 + 拆分 逆序输出 (上面 方法1 纯手动)
        String[] sp = s.replaceAll("[^a-zA-Z]", " ").split(" ");
        for (int i = sp.length - 1; i >= 0; i--) {
            res = res + " " + sp[i];
        }
        System.out.print(res.substring(1));// 头多个空格
    }
}

发表于 2025-01-27 12:42:17 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        System.out.print(reverseWords(str));


    }
    public static String reverseWords(String str) {
        String s = str.replaceAll("[^a-zA-Z0-9]"," ");
        // 使用空格分割句子成单词数组
        String[] words = s.split(" ");
        // 创建一个StringBuilder用于构建逆序后的句子
        StringBuilder sb = new StringBuilder();

        // 逆序遍历单词数组
        for (int i = words.length - 1; i >= 0; i--) {
            // 将单词添加到StringBuilder
            sb.append(words[i]);
            // 如果不是最后一个单词,添加一个空格
            if (i > 0) {
                sb.append(" ");
            }
        }

        // 返回逆序后的句子
        return sb.toString();
    }
}

发表于 2024-11-11 21:43:19 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String word = scanner.nextLine();
            String str = "";
            //特殊字符变为空格
            for (int i = 0; i < word.length(); i++) {
                char ch = word.charAt(i);
                if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
                    str += ch;
                } else {
                    str += " ";
                }
            }
            String words[] = str.split(" ");
            String reverseWord = "";
            //倒置数据
            for (int i = 0; i < words.length; i++) {
                reverseWord += words[words.length - i - 1] + " ";
            }

            String reverseWords[] = reverseWord.split(" ");
            String finalString = "";
            for (int i = 0; i < reverseWords.length; i++) {
                finalString += reverseWords[i] + " ";
            }
            // 将多余空格置换为一个空格
            finalString = finalString.replaceAll("\\s+", " ");
            System.out.println(finalString.trim());

        }
        scanner.close();
    }
}

发表于 2024-09-25 21:16:45 回复(0)
import java.util.Scanner;
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String[] arr = in.nextLine().split("[^A-Za-z]");
            List<String> l = new ArrayList<String>();
            for (String a : arr) {
                l.add(a);
            }
            Collections.reverse(l);
            System.out.println(String.join(" ", l));
        }
        in.close();
    }
}
发表于 2024-09-10 16:48:47 回复(0)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
         Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        str = str.replaceAll("[^a-zA-Z]+"," ");
        List<String> list = new ArrayList<>();
        list = Arrays.asList(str.split(" "));
        Collections.reverse(list);
        String strResult = String.join(" ",list);
        System.out.println(strResult);
    }
}

发表于 2024-09-07 18:11:14 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        char[] res = str.toCharArray();
        reverse(res, 0, res.length - 1);
        int start = 0;
        for (int i = 0; i < res.length; i++) {
            if (res[i] >= 'a' && res[i] <= 'z' || res[i] >= 'A' && res[i] <= 'Z') {
                continue;
            } else {
                res[i] = ' ';
            }
        }
        for (int i = 0; i < res.length; i++) {
            if (res[i] != ' ' && (i == 0 || res[i - 1] == ' ')) {
                start = i;
            }
            if (res[i] != ' ' && (i == res.length - 1 || res[i + 1] == ' ')) {
                reverse(res, start, i);
            }
        }
        System.out.println(new String(res));
    }

    public static void reverse(char[] array, int l, int r) {
        while (l < r) {
            char temp = array[l];
            array[l] = array[r];
            array[r] = temp;
            l++;
            r--;
        } //O(n)
    }
}
发表于 2024-08-19 11:39:50 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        String[] strArr = str.split("[^A-Za-z]");

        for(int i = strArr.length -1; i >= 0; i--) {
            if (strArr[i].length() > 0) {
                System.out.print(strArr[i] + " ");
            }
        }
    }
}
发表于 2024-06-03 22:09:16 回复(0)
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        List<String> list = new ArrayList<>();
        String strTemp = new String();
        for(int i = 0;i<str.length();i++){
            char c = str.charAt(i);
            if(c <= 'z' && c>='a'){
                strTemp += c;
            }else if(c <='Z' && c>='A'){
                strTemp += c;
            }else{
                if(strTemp != null && strTemp.length()>0){
                    list.add(strTemp);
                }
                strTemp = "";
            }
        }
        list.add(strTemp);
        Collections.reverse(list);
        String strResult = String.join(" ",list);
        System.out.println(strResult);
    }
}

编辑于 2024-04-25 15:56:18 回复(0)
借助栈结构先进后出的特点,天生适合做倒序。大小写字母的ascII码刚好也记得,这样就可以了
Stack<String> stack = new Stack<>();

Scanner in = new Scanner(System.in);
String str = in.nextLine();

String tempstr = "";
for(int i=0;i<str.length();i++){
char c = str.charAt(i);
if(c >= 97 && c <=122) {
tempstr += c;
}else if(c>=65 && c<=90) {
tempstr += c;
}else {
stack.push(tempstr);
tempstr = "";
}
}
stack.push(tempstr);

String resp = stack.pop();
while(!stack.isEmpty()) {
resp = resp + " " + stack.pop();
}

System.out.println(resp);

编辑于 2024-04-18 18:40:28 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String s = in.nextLine();
            StringBuilder sb = new StringBuilder(s);
            int count = 0;
            int nullIndex = -1;
            for (int i = 0; i < sb.length(); i++) {
                char ch = sb.charAt(i);
                if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
                    //将从nullIndex开始,长度为count的字符全部置为空范围是左闭右开
                    if (nullIndex != -1) {
                        sb.replace(nullIndex, nullIndex + count, " ");
                        count = 0;
                        nullIndex = -1;
                    }
                    continue;
                } else {
                    //这种情况就是非构成单词的字符了
                    if (nullIndex == -1)
                        nullIndex = i;
                    count++;
                }
            }
            String [] arr = sb.toString().split(" ");
            int left = 0;
            int right = arr.length - 1;
            while(left < right){
                swap(arr, left++, right--);
               
            }
            String res = String.join(" ", arr);
            System.out.println(res);
        }
    }

    public static void swap(String [] arr, int i, int j){
        String ch = arr[i];
        arr[i] = arr[j];
        arr[j] = ch;
    }
}
发表于 2024-03-29 10:56:20 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String inString = in.nextLine();
            List<String> arr = new ArrayList<>();
            String s = "";
            for (int i = 0 ; i < inString.length() ; i++) {
                if (Character.isLetter(inString.charAt(i))) {
                    s += inString.charAt(i);
                    //对最后一个单词单独添加
                    if (!"".equals(s) && i == inString.length() - 1) {
                        arr.add(s);
                    }
                } else {
                    if (!"".equals(s)) {
                        arr.add(s);
                    }
                    s = "";
                }
            }
            //倒排
            Collections.reverse(arr);

            String res = "";
            for (String part : arr) {
                res += part + " ";
            }
            System.out.println(res);
        }
    }
}

发表于 2023-12-28 10:46:24 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String str = in.nextLine();

        int right = str.length() - 1;
        int left = right;
        StringBuffer res = new StringBuffer();
        while (right>=0) {

            while (left >= 0 && Character.isLetter(str.charAt(left))) {
                left--;
            }

            res.append(str.substring(left + 1, right + 1));
            if(left != 0){
                res.append(" ");
            }
            while(left>=0 && !Character.isLetter(str.charAt(left))){
                left--;
            }
            right = left;
        }

        System.out.println(res.toString());

    }
}
使用双指针解决,和H13句子逆序相同,一并解决
编辑于 2023-12-04 04:16:12 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] a = in.nextLine().split("[^a-zA-Z]");
        for(int i = a.length-1 ;i>=0;i--){      
            System.out.print(a[i]+" ");
        }        
    }
}
正则固然好用,就是还不熟练
发表于 2023-10-23 03:59:24 回复(0)
强烈建议大家学一下正则表达式,真的超好用
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        String[] strs = str.split("[^a-zA-Z]");
        for (int i = strs.length-1; i >= 0; i--) {
            System.out.print(strs[i]+" ");
        }
    }
}


发表于 2023-09-27 17:27:07 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str=in.nextLine();
        int index=str.length()-1;
        for(int i=index;i>=0;i--){
            if(!((str.charAt(i)>='A'&&str.charAt(i)<='Z')||
                    (str.charAt(i)>='a'&&str.charAt(i)<='z'))){
                for(int j=i+1;j<str.length();j++){
                    if((str.charAt(j)>='A'&&str.charAt(j)<='Z')||
                            (str.charAt(j)>='a'&&str.charAt(j)<='z')){
                        if(j==str.length()-1){
                            System.out.print(str.charAt(j)+" ");
                        }else {
                            System.out.print(str.charAt(j));
                        }
                    }else {
                        System.out.print(" ");
                        break;
                    }
                }
            }else if(((str.charAt(i)>='A'&&str.charAt(i)<='Z')||
                    (str.charAt(i)>='a'&&str.charAt(i)<='z'))&&i==0){
                for(int j=0;j<str.length();j++){
                    if((str.charAt(j)>='A'&&str.charAt(j)<='Z')||
                            (str.charAt(j)>='a'&&str.charAt(j)<='z')){
                        System.out.print(str.charAt(j));
                    }else {
                        break;
                    }
                }
            }
        }
    }
}

发表于 2023-09-17 16:23:38 回复(0)