【Leetcode】2047. Number of Valid Words in a Sentence

题目地址:

https://leetcode.com/problems/number-of-valid-words-in-a-sentence/

给定一个只含英文小写字母,数字,-! . ,和空格的字符串 s s s,问其有多少个合法单词。单词由空格隔开。一个单词合法当且仅当:
1、它不含数字;
2、它最多含一个-,并且其不位于首尾;
3、它最多含一个! . ,,且只能位于结尾。

代码如下:

public class Solution {
    public int countValidWords(String sentence) {
    	// 按空格隔开
        String[] ss = sentence.split("\\s+");
        int res = 0;
        for (String s : ss) {
            if (!s.isEmpty() && check(s)) {
                res++;
            }
        }
        
        return res;
    }
    
    boolean check(String s) {
        int h = 0, m = 0;
        char[] ch = s.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            if (Character.isDigit(ch[i]) || ch[i] == ' ') {
                return false;
            }
            if (ch[i] == '-') {
                h++;
                if (h >= 2) {
                    return false;
                } else if (i == 0 || i == ch.length - 1 || !Character.isLetter(ch[i - 1]) || !Character.isLetter(ch[i + 1])) {
                    return false;
                }
            }
            
            if (ch[i] == '!' || ch[i] == '.' || ch[i] == ',') {
                m++;
                if (m >= 2) {
                    return false;
                }
                
                if (i != ch.length - 1) {
                    return false;
                }
            }
        }
        
        return true;
    }
}

时空复杂度 O ( l s ) O(l_s) O(ls)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值