题目要求
仅由小写字母、连字符和/或标点(不含数字)。
至多一个 连字符 ‘-’ 。如果存在,连字符两侧应当都存在小写字母(“a-b” 是一个有效单词,但 “-ab” 和 “ab-” 不是有效单词)。
至多一个 标点符号。如果存在,标点符号应当位于 单词 的 末尾 。
这里给出几个有效单词的例子:“a-b.”、“afad”、“ba-c”、“a!” 和 “!” 。
问题解答
用正则也可以,这边用官方的解答
public class Ten {
public static boolean isValid(String word) {
int n = word.length();
boolean hasHyphens = false;
for (int i = 0; i < n; i++) {
if (Character.isDigit(word.charAt(i))) {
return false;
} else if (word.charAt(i) == '-') {
if (hasHyphens == true || i == 0 || i == n - 1 || !Character.isLetter(word.charAt(i - 1)) || !Character.isLetter(word.charAt(i + 1))) {
return false;
}
hasHyphens = true;
} else if (word.charAt(i) == '!' || word.charAt(i) == '.' || word.charAt(i) == ',') {
if (i != n - 1) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String sentence = "ba-c";
System.out.println(isValid(sentence));
}
}
知识拓展
如果是多个字符串用空格相连,例如
cat and !dog
判断其中有多少个有效单词,可以通过空格将它们分隔开来,然后再调用上述方法进行逐个判断,
public static int countValidWords(String sentence) {
int n = sentence.length();
int l = 0, r = 0;
int ret = 0;
while (true) {
while (l < n && sentence.charAt(l) == ' ') {
l++;
}
if (l >= n) {
break;
}
r = l + 1;
while (r < n && sentence.charAt(r) != ' ') {
r++;
}
if (isValid(sentence.substring(l, r))) { // 判断根据空格分解出来的 token 是否有效
ret++;
}
l = r + 1;
}
return ret;
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-valid-words-in-a-sentence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。