LeetCode练习<一> 判断大写字母的位置

    LeetCode练习.Java题目

题目要求:

*  Given a word, you need to judge whether the usage of capitals in it is right or not.
*  We define the usage of capitals in a word to be right when one of the following cases holds:
*  All letters in this word are capitals, like "USA".
*  All letters in this word are not capitals, like "leetcode".
*  Only the first letter in this word is capital if it has more than one letter, like "Google".
*  Otherwise, we define that this word doesn't use capitals in a right way.
题目的要求是,输入一个字符串,判断字符串中大写字母的位置 , 以下三种情况可以返回true , 其余的返回false:

1 全部是大写字母

2 全部是小写字母

3 只有第一个字母是大写字母

    /** 
     * 我的思路是定义如下两个变量 , count和seq . 然后将字符串转换成StringBuilder , 这样就可以一个一个字母的访问了 * count用于统计大写字母的个数 , seq用于记录大写字母的位置 
     * isUpperCase 用于判断字母是否为大写字母,是就为true , 不是就为 false
     * count==0对应于第3种情况
     * count==word.length 对应与第一种情况
     * count == 1 , 且seq == 0(大写字母位于第0个位置)则对应于第2种情况
     * @param word
     * @return
     */
    public static boolean detectCapitalUse(String word){
        int count= 0;   //统计大写字母的个数
        int seq = 0;
        StringBuilder strBuild = new StringBuilder(word);
        for (int i = 0; i < strBuild.length(); i++) {
            if(Character.isUpperCase(strBuild.charAt(i))){
                count++;
                seq = i;
            }
        }
        System.out.println(strBuild.length() + "\t" + count + "\t" + seq);
        if(strBuild.length() == count || count == 0 ||(count == 1 && seq ==0)) {
            return true;
        }
        else{
            return false;
        }
    }
参考LeetCode上大神的写法:

    /**
     * 利用正则化的方法
     * 全是大写字母[A-Z]+
     * 全是小写字母[a-z]+
     * 第一个大写后面的都小写[A-Z][a-z]+
     * @param word
     * @return
     */
    public static boolean detectCapitalUse1(String word) {
        return word.matches("[A-Z]+|[a-z]+|[A-Z][a-z]+");
    }

正则化确实厉害 , 这种思路更加厉害 .


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值