翻转单词顺序列

题目
输入一个英文句子, 翻转句子中单词的顺序, 但单词内字符的顺序不变. 为简单起见, 标点符号和普通字母一样处理. 例如输入字符串"Iam a student.", 则输出"student. a am I"。
解题思路
(1)先翻转单词,再翻转顺序列(不借助额外的空间)
源代码

public class ReverseSentence {
    public static String reverseSentence(String str) {
        int n = str.length();
        char[] chars = str.toCharArray();
        int i = 0, j = 0;
        while (j <= n) {
            if (j == n || chars[j] == ' ') {//转换单个单词
                reverse(chars, i, j - 1);
                i = j + 1;
            }
            j++;
        }
        reverse(chars, 0, n - 1);//翻转整个字符数组
        return new String(chars);
    }

    private static void reverse(char[] chars, int i, int j) {
        while (i < j)
            swap(chars, i++, j--);
    }

    private static void swap(char[] chars, int i, int j) {//交换字符串数组第i和第j位置的元素
        char c = chars[i];
        chars[i] = chars[j];
        chars[j] = c;
    }

    public static void main(String[] args) {
        System.out.println(reverseSentence("I am a student!"));
    }
}

(2)将字符串按空格切割成字符串数组,以数组长度的一半为原点,将距离原点相等的下标数组元素进行交换,最后遍历输出数组元素即可。
源代码

public class ReverseSentence {
	public static String reverseSentence1(String str) {
        String[] strings = str.split(" ");
        String result = "";
        int length = strings.length;
        for (int i = 0; i < strings.length / 2; i++) {
            String temp = strings[i];
            strings[i] = strings[length - i - 1];
            strings[length - i - 1] = temp;
        }
        for (int i = 0; i < length; i++) {
            result += strings[i];
            if (i != length - 1)
                result += " ";
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(reverseSentence1("I am a student!"));
    }
}

(2)借用辅助空间栈实现,Stack
源代码

package Arithmetic;

import java.util.Scanner;
import java.util.Stack;

public class WordReverse {
    private static Stack<String> stack = new Stack<>();
    public static String wordReverse(String string) {
        stack.clear();
        String[] strings = string.split(" ");
        String result = "";
        for (int i = 0; i < strings.length; i++) {
            if (!"".equals(strings[i])){
                stack.push(strings[i]);
            }
        }
        int size = stack.size();
        for (int j = 0; j < size; j++) {
            result += stack.pop();
            if (j < size - 1)
                result += " ";
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        System.out.println(wordReverse(s));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值