相关信息:
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;
}
}