Merge pull request #818 from furahadamien/wordCount

Word count
This commit is contained in:
Yang Libin
2019-08-28 14:09:28 +08:00
committed by GitHub
2 changed files with 47 additions and 0 deletions

View File

@ -16,6 +16,7 @@ public class CountWords {
String str = input.nextLine(); String str = input.nextLine();
System.out.println("Your text has " + wordCount(str) + " word(s)"); System.out.println("Your text has " + wordCount(str) + " word(s)");
System.out.println("Your text has " + secondaryWordCount(str) + " word(s)");
input.close(); input.close();
} }
@ -25,4 +26,25 @@ public class CountWords {
return s.trim().split("[\\s]+").length; return s.trim().split("[\\s]+").length;
} }
/**
* counts the number of words in a sentence but ignores all potential
* non-alphanumeric characters that do not represent a word. runs in O(n) where
* n is the length of s
*
* @param s String: sentence with word(s)
* @return int: number of words
*/
private static int secondaryWordCount(String s) {
if (s == null || s.isEmpty())
return 0;
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isLetter(c) || Character.isDigit(c))
sb.append(c);
}
s = sb.toString();
return s.trim().split("[\\s]+").length;
}
} }

View File

@ -22,4 +22,29 @@ class Palindrome {
return SecondWay(x.substring(1, x.length() - 1)); return SecondWay(x.substring(1, x.length() - 1));
} }
/**
* This method ignores all non-alphanumeric characters and case runs in O(n)
* where n is the length of s
*
* @param s String to check
* @return true if s is palindrome else false
*/
public boolean isPalindrome(String s) {
s = s.toLowerCase().trim();
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isLetter(c) || Character.isDigit(c))
sb.append(c);
}
s = sb.toString();
int start = 0;
int end = s.length() - 1;
while (start <= end) {
if (s.charAt(start++) != s.charAt(end--))
return false;
}
return true;
}
} }