字符数组中单词反转问题

单词反转问题

“hello world” —–> “world hello”

输入:字符数组
输出:反转后的字符串

思路:
先将整个字符数组反转,然后根据空格来确定各个单词的起始位置并单独进行反转。

代码如下:

import java.util.Arrays;

/**
 * Created by Administrator on 2017/9/12.
 * 翻转单词 如“hello world”翻转为“world hello”
 *
 */
public class Reverse {
    public static void reverse(char []a){
        if(a.length == 0 || a == null)  return;
        int beg = 0;
        int end = a.length-1;
        reverse_word(a,beg,end);//先反转整个字符数组
        beg = -1;
        end = -1;
        for (int i = 0; i < a.length; i++) {
            //单词开始位置
            if (beg == -1 && a[i] != ' '){
                beg = i;
                continue;
            }
            //单词结束位置的后一位
            if (beg != -1 && a[i] == ' '){
                end = i - 1;
                reverse_word(a,beg,end);
                beg = -1;
                end = -1;
                continue;
            }
            //字符串数组结尾位置
            if (beg != -1 && i == a.length - 1){
                end = i;
                reverse_word(a,beg,end);
                break;
            }
        }
        String s = String.valueOf(a);
        System.out.println(s);
    }

    public static void reverse_word(char []a,int beg,int end){
        while(beg < end){
            char tem = a[beg];
            a[beg] = a[end];
            a[end] = tem;
            beg++;
            end --;
        }
    }

    public static void main(String args[]){
        String s = "hello  world  ";
        char []a = s.toCharArray();
        reverse(a);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值