while (true){ while (left<n&&sentence.charAt(left)==' '){ left++; } if (left>=n) break; right = left+1; while (right <n&&sentence.charAt(right)!=' '){ right++; } if (isValidWord(sentence.substring(left,right))){ ans++; } left = right + 1; }
publicintcountValidWords(String sentence){ int ans = 0,left=0,right=0; int n = sentence.length(); while (true){ while (left<n&&sentence.charAt(left)==' '){ left++; } if (left>= n) break; right = left+1; while (right<n&&sentence.charAt(right)!=' '){ right++; } if(isValidWord(sentence.substring(left,right))){ ans++; } left = right + 1; } return ans; } publicbooleanisValidWord(String word){ int n = word.length(); boolean flag = false; for(int i=0; i<n;i++){ if (word.charAt(i)>='0'&&word.charAt(i)<='9'){ // 判定为数字 returnfalse; } elseif (word.charAt(i)==','||word.charAt(i)=='.'||word.charAt(i)=='!'){ if (i!=n-1){ returnfalse; } } elseif (word.charAt(i)=='-'){ if (flag||i==0||i==n-1||!Character.isLetter(word.charAt(i-1))||!Character.isLetter(word.charAt(i+1))){ returnfalse; } flag = true; } } returntrue; }