LeetCode-520. Detect Capital (JAVA)大写字母的合法性

520. Detect Capital

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:

  1. All letters in this word are capitals, like "USA".
  2. All letters in this word are not capitals, like "leetcode".
  3. 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.

1,如果全是小写字母,那么是有效的

2,如果全是大写字母,那么是有效的

3,如果第一个字母大写,后面的字母全是小写(如果有),那么也是有效的。

其余情况都是无效的

我的AC,简单直观

第一种:

public boolean detectCapitalUse2(String word) {
	// 注意长度<=1
	if (word == null || word.length() <= 1)
		return true;
	char fir = word.charAt(0);
	char sec = word.charAt(1);
	boolean f = Character.isUpperCase(fir);
	boolean s = Character.isUpperCase(sec);
	// 第一个字母小写,第二个字母大写
	if (!f && s)
		return false;
	// 第一个字母大写,第二个字母大写
	if (f && s) {
		for (int i = 2; i < word.length(); i++)
			// 如果之后出现小写,返回false(前两个字母大写)
			if (Character.isLowerCase(word.charAt(i)))
				return false;
	}
	// 如果第二个字母小写
	else if (!s) {
		for (int i = 2; i < word.length(); i++)
			// 如果之后出现大写,返回false(第二个字母小写)
			if (Character.isUpperCase(word.charAt(i)))
				return false;
	}
	return true;
}

第二种:使用substring

public boolean detectCapitalUse(String word) {
	// 长度小于2,返回true
	if (word.length() < 2)
		return true;
	// 如果全是大写字母
	if (word.toUpperCase().equals(word))
		return true;
	// 如果第一个字母之后全是小写(第一个字母大小写无所谓)
	if (word.substring(1).toLowerCase().
			equals(word.substring(1)))
		return true;
	return false;
}
第三种来源于discuss(代理解)

public boolean detectCapitalUse(String word) {
	if (word == null || word.length() == 0)
		return true;
	boolean first = false;
	boolean all = false;
	for (int i = 0; i < word.length(); i++) {
		char c = word.charAt(i);
		if (c >= 'A' && c <= 'Z') {
			if (i == 0) {
				first = true;
				all = true;
			} else {
				if (!all)
					return false;
			}
		} else {
			if (all && i > 1)
				return false;
			all = false;
		}
	}
	return true;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值