LeetCode2047. 句子中的有效单词数

相关信息:

LeetCode链接:
https://leetcode-cn.com/problems/number-of-valid-words-in-a-sentence/

代码:

//作者:LeetCode-Solution
public class L2047 {
    public static void main(String[] args) {
        //Test
        SolutionL2047 solution2047 = new SolutionL2047();
        String sentence = "alice and  bob are playing stone-game10";
        int ans = solution2047.countValidWords(sentence);
        System.out.println(ans);
    }
}

class SolutionL2047 {
    public int countValidWords(String sentence) {
        int length = sentence.length();
        int left = 0, right = 0;
        int ret = 0;

        while (true) {
            while (left < length && sentence.charAt(left) == ' ') {
                left++;
            }
            if (left >= length) {
                break;
            }
            right = left + 1;
            while (right < length && sentence.charAt(right) != ' ') {
                right++;
            }
            // Judge whether consecutive strings comply with the rules
            if (isValid(sentence.substring(left, right))) {
                ret++;
            }
            //update left index
            left = right + 1;
        }
        return ret;
    }

    public boolean isValid(String word) {
        int length = word.length();
        boolean hasHyphens = false;
        for (int i = 0; i < length; i++) {
            //如果word中有数字
            if (Character.isDigit(word.charAt(i))) {
                return false;
            }

            /*if there is "-" in word and the following occurs,
             * two "-", starting with "-" and ending with "-",
             * the first digit of "-" is not a letter, and the last digit of "-" is not a letter
             * description word is not a qualified alphabetic string
             * */
            else if (word.charAt(i) == '-') {
                if (hasHyphens || i == 0 || i == length - 1 || !Character.isLetter(word.charAt(i - 1)) || !Character.isLetter(word.charAt(i + 1))) {
                    return false;
                }
                hasHyphens = true;
                /*if '!' , ',' , '.' not at the end of word
                 * description word is not a qualified alphabetic string
                 * */
            } else if (word.charAt(i) == '!' || word.charAt(i) == '.' || word.charAt(i) == ',') {
                if (i != length - 1) {
                    return false;
                }
            }
        }
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值