Skip to content

Commit c5e32ea

Browse files
authored
Merge pull request #818 from furahadamien/wordCount
Word count
2 parents 11864ca + 4ddbaca commit c5e32ea

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

Others/CountWords.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ public static void main(String[] args) {
1616
String str = input.nextLine();
1717

1818
System.out.println("Your text has " + wordCount(str) + " word(s)");
19+
System.out.println("Your text has " + secondaryWordCount(str) + " word(s)");
1920
input.close();
2021
}
2122

@@ -25,4 +26,25 @@ private static int wordCount(String s) {
2526
return s.trim().split("[\\s]+").length;
2627
}
2728

29+
/**
30+
* counts the number of words in a sentence but ignores all potential
31+
* non-alphanumeric characters that do not represent a word. runs in O(n) where
32+
* n is the length of s
33+
*
34+
* @param s String: sentence with word(s)
35+
* @return int: number of words
36+
*/
37+
private static int secondaryWordCount(String s) {
38+
if (s == null || s.isEmpty())
39+
return 0;
40+
StringBuilder sb = new StringBuilder();
41+
for (char c : s.toCharArray()) {
42+
if (Character.isLetter(c) || Character.isDigit(c))
43+
sb.append(c);
44+
}
45+
s = sb.toString();
46+
return s.trim().split("[\\s]+").length;
47+
48+
}
49+
2850
}

Others/Palindrome.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,29 @@ public boolean SecondWay(String x) {
2222

2323
return SecondWay(x.substring(1, x.length() - 1));
2424
}
25+
26+
/**
27+
* This method ignores all non-alphanumeric characters and case runs in O(n)
28+
* where n is the length of s
29+
*
30+
* @param s String to check
31+
* @return true if s is palindrome else false
32+
*/
33+
public boolean isPalindrome(String s) {
34+
s = s.toLowerCase().trim();
35+
StringBuilder sb = new StringBuilder();
36+
for (char c : s.toCharArray()) {
37+
if (Character.isLetter(c) || Character.isDigit(c))
38+
sb.append(c);
39+
}
40+
s = sb.toString();
41+
int start = 0;
42+
int end = s.length() - 1;
43+
while (start <= end) {
44+
if (s.charAt(start++) != s.charAt(end--))
45+
return false;
46+
47+
}
48+
return true;
49+
}
2550
}

0 commit comments

Comments
 (0)