【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)

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/120945082