字符串归一化

输入:字符数组;
输出:字符数组;转换规则:单词(非空格字符认为是单词构成)间保留一个空格,最开始和最结尾的地方不保留空格,奇数个单词首字母大写,其他小写。
要求:时间复杂度O(n),空间复杂度O(1),即char[]原地转换。
举例:输入" I am a good student",输出"I am A good Student"。

public class NormalizdCharArray {

    char space = ' ';
//    输入"  I am a good     student",输出"I am A good Student"。
    public void normalizdCharArray(char[] ch){
        if(ch == null || ch.length == 0){
            return;
        }
        int start = 0;
        int index = 0;
//        去除开始的空格
        while(ch[start] == space){
            start ++;
        }
//         去除重复的空格
        for(int i = start; i < ch.length - 1; i ++){
            if(ch[i] == space && ch[i+1] == space){
                continue;
            }
            ch[index ++] = ch[i];
        }
            ch[index] = ch[ch.length - 1];

        int amount = 1;

//        大小写转换
        for(int i = 0; i < index+1; i ++){
            if((amount & 1) == 1 && ifInitial(ch,i)){
                ch[i] = Character.toUpperCase(ch[i]);
            }else {
                ch[i] = Character.toLowerCase(ch[i]);
            }
            if(ch[i] == space){
                amount ++;
            }
        }
        for(int i = 0; i < index; i ++){
            System.out.print(ch[i]);
        }
       if(ch[index] != space){
           System.out.print(ch[index]);
       }
    }

//    判断是否首字母
    private boolean ifInitial(char[] ch, int i) {
        if(i == 0 || ch[i-1] == space){
            return true;
        }else {
            return false;
        }
    }


    public static void main(String[] args){
        String example = "  I aM a gooOd     stUdent  ";
        new NormalizdCharArray().normalizdCharArray(example.toCharArray());
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值