字符串归一化

来源:互联网 发布:最好的erp软件 编辑:程序博客网 时间:2024/06/03 16:00

输入:字符数组;
输出:字符数组;转换规则:单词(非空格字符认为是单词构成)间保留一个空格,最开始和最结尾的地方不保留空格,奇数个单词首字母大写,其他小写。
要求:时间复杂度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 0
原创粉丝点击