首页 > 试题广场 >

单词倒排

[编程题]单词倒排
  • 热度指数:365619 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

对字符串中的所有单词进行倒排。

说明:

1、构成单词的字符只有26个大写或小写英文字母;

2、非构成单词的字符均视为单词间隔符;

3、要求倒排后的单词间隔符以一个空格表示;如果原字符串中相邻单词间有多个间隔符时,倒排转换后也只允许出现一个空格间隔符;

4、每个单词最长20个字母;

数据范围:字符串长度满足

输入描述:

输入一行,表示用来倒排的句子



输出描述:

输出句子的倒排结果

示例1

输入

I am a student

输出

student a am I
示例2

输入

$bo*y gi!r#l

输出

l r gi y bo
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)
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = br.readLine();

        System.out.println(reverse1(line));
    }

    /**
     * 字符串单词反转
     *
     * @param line
     */
    private static String reverse1(String line) {
        StringBuilder result = new StringBuilder();
        StringBuilder sb = new StringBuilder();
        for (int i = line.length() -1; i >= 0; i--) {
            char c = line.charAt(i);
            if (Character.isLetter(c)){
                sb.append(c);
            }else {
                result.append(sb.reverse());
                result.append(" ");
                sb.delete(0, sb.length());
            }
        }

        result.append(sb.reverse());
        return result.toString();
    }
}

发表于 2023-08-08 09:14:37 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
      Scanner in = new Scanner(System.in);
        StringBuilder stringBuilder = new StringBuilder();
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String s = in.nextLine();
            char[] chars = s.toCharArray();
            for (char aChar : chars) {
                if(!(aChar>='a' && aChar <= 'z' || aChar >= 'A' && aChar <= 'Z')) {
                    aChar = ' ';
                    stringBuilder.append(aChar);
                }else{
                    stringBuilder.append(aChar);
                }

            }
            String[] s1 = stringBuilder.toString().split(" ");
            for (int i = s1.length - 1; i >= 0; i--) {
                System.out.print(s1[i] + " ");
            }

        }
        in.close();
    }
}
发表于 2023-08-07 23:48:23 回复(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 str = in.nextLine();
            // System.out.println(str);
            ArrayList<String> list = getStrArr(str);
            // System.out.println(list);
            int n = list.size();
            for(int i = n-1;i>-1;i--){
                if(i==0){
                    System.out.print(list.get(i));
                } else {
                    System.out.print(list.get(i)+" ");
                }
            }
        }
    }

    public static ArrayList<String> getStrArr(String input) {
        ArrayList<String> wordList = new ArrayList<String>();
        int n = input.length();

        String tempStr = "";
        for (int i = 0; i < n; i++) {
            char tempChar = input.charAt(i);
            // System.out.println(tempChar);

            if ((tempChar >= 'A' && tempChar <= 'Z') || (tempChar >= 'a' &&
                    tempChar <= 'z')) {
                tempStr = tempStr + tempChar;
                if (i == n - 1) {
                    wordList.add(tempStr);
                }
            } else {
                if (!tempStr.equals("")) {
                    wordList.add(tempStr);
                    // System.out.println(tempStr);
                    tempStr = "";
                    continue;
                } else {
                    continue;
                }
            }
        }

        return wordList;

    }
}

发表于 2023-07-05 22:13:07 回复(0)
import java.util.*;
public class Main {
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        String[] src = in.nextLine().split("[^A-Za-z]");
        StringBuilder srcs = new StringBuilder();
        for(int i = src.length-1;i >= 0;i--)
        {
            srcs.append(src[i]).append(" ");
        }
        System.out.println(srcs.toString().trim());
    }
}
发表于 2023-07-02 22:14:24 回复(0)
import java.util.Scanner;
import java.util.LinkedList;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String line = in.nextLine();
        in.close();
        //最初概要思路:
        //遇到一个字符
        //1,是大小写字母
        //          前一个不是特殊字符,拼接
        //          前一个是特殊字符,创建
        //2,是特殊字符
        //          前一个不是特殊字符,存字符入数组
        //          前一个是特殊字符,跳过
        /* 编码思路
            用双指针,index ,left , right
            开始时 left==right ,notLetter=true
            遇到字母 right++
            遇到特殊字符   if(right >= left && !notLetter) 截取,
                    再遇到字母,left=right=index,notLetter=false
            到末尾,再判断一次 if(right >= left && !notLetter) 截取
         */
        int index=0 ,left=0 , right = 0;
        boolean notLetter = true;
        LinkedList<String> lsList = new LinkedList<>();
        char[] charArray = line.toCharArray();
        while (index < charArray.length) {
            if (Character.isLetter(charArray[index])) {
                right = notLetter ? index : right +1;
                if (notLetter) {
                    left = index;
                    notLetter = false;
                }
            }else {
                if(right >= left && !notLetter){
                    lsList.push(String.copyValueOf(charArray,left,right-left+1));
                }
                notLetter = true;
            }
            index++;
        }
        if(right >= left && !notLetter){
            lsList.push(String.copyValueOf(charArray,left,right-left+1));
        }
        while (!lsList.isEmpty()) {
            System.out.print(lsList.pop());
            if (lsList.size() > 0) {
                System.out.print(" ");
            }
        }
    }
}

发表于 2023-06-11 10:48:28 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String a = in.nextLine();
        StringBuilder bud = new StringBuilder();
        // 将除了字母外的字符全部替换成空格
        String s = a.replaceAll("[^a-zA-Z]", " ");
        //使用分隔符分隔
        String[] s1 = s.split(" ");
        //循环插入
        for (int i = s1.length-1; i >= 0; i--) {
            bud.append(s1[i] +" ");
        }
        System.out.println(bud);
    }
}
这样也可以
发表于 2023-05-29 14:43:05 回复(0)
import java.util.ArrayList;
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);
        // 注意 hasNext 和 hasNextLine 的区别
        String str = in.nextLine();
        String[] array = str.split(" ");
        int size = array.length;
        List<String> list = new ArrayList<>();
        String s;
        for (int i = size - 1; i >= 0; i--) {
            s = array[i];
            for (int j = 0; j < array[i].length(); j++) {
                char ch = array[i].charAt(j);
                // System.out.print(ch+" ");
                if (ch < 'A' || (ch > 'Z' && ch < 'a') || ch > 'z')
                    s = s.replace(ch, ' ');
            }
            // System.out.print(s);
            if (s.contains(" ")) {
                String[] st = s.split(" ");
                for (int k = st.length - 1; k >= 0; k--)
                    list.add(st[k]);
            }else list.add(s);

        }
        list.forEach(s1->System.out.print(s1+" "));
    }
}
纯纯暴力解法
发表于 2023-05-27 20:17:05 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String str=in.nextLine();
        Stack<String> stack=new Stack<>();
        String tmp="";
        for(int i=0;i<str.length();i++){
            if(str.charAt(i)>='a'&&str.charAt(i)<='z'||str.charAt(i)>='A'&&str.charAt(i)<='Z'){
                tmp+=str.charAt(i);
            }else{
                if(tmp!=""){
                    stack.push(tmp);
                }
                tmp="";
            }
        }
        if(tmp!=""){
            stack.push(tmp);
        }
        tmp="";
        while(!stack.isEmpty()){
            tmp+=stack.pop()+" ";
        }
        tmp=tmp.substring(0,tmp.length()-1);
        System.out.print(tmp);
    }
}

发表于 2023-05-26 18:59:58 回复(0)
好像测试用例都没有满足第三个条件的,我中间一堆数字运行一堆空格的程序都还能通过。。。无语了
发表于 2023-05-25 20:44:49 回复(0)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String str = in.nextLine();
        String alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        TreeSet<Integer> treeSet = new TreeSet<>();
        // 遍历字符串 str,找出不属于 26 个字母的字符的索引
        for (int i = 0; i < str.length(); i++) {
            String c = String.valueOf(str.charAt(i));
            if (!alpha.contains(c)) {
                // 不属于 26 个字母,算是分隔符或空格
                treeSet.add(i); // 记录下索引
            }
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == ' ') {
                sb.append(c);
                continue;
            }
            if (treeSet.contains(i)) {
                // 非空格,非字母,替换
                sb.append(" ");
                continue; // 跳过
            }
            sb.append(c);
        }

        String s = sb.toString().trim();
        if (s.equals("")) {
            s = str;
        }
        String[] arr = s.split(" ");
        for (int i = arr.length - 1; i >= 0; i--) {
            System.out.print(arr[i] + " ");
        }

    }
}

发表于 2023-05-22 17:00:48 回复(0)
public class Test01 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String str = in.nextLine();
            //收集单词
            StringBuffer sb = new StringBuffer();
            //收集结果
            StringBuffer result = new StringBuffer();
            //后续遍历字符
            for (int i = str.length()-1; i >=0 ; i--) {
                char c = str.charAt(i);
                //遇到单词收集
                if(Character.isLetter(c)){
                    sb.append(c);
                }else{
                    //不是单词,并且单词StringBuffer不为空,
                    //将单词反转收集结果,清空单词StringBuffer
                    if(!sb.toString().equals("")){
                        result.append(sb.reverse()+" ");
                        sb = new StringBuffer();
                    }
                }
            }
            //将剩余的单词收集起来
            result.append(sb.reverse());
            System.out.println(result.toString());
        }
    }
}

发表于 2023-05-16 21:32:19 回复(0)