Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Others/CountWords.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public static void main(String[] args) {
String str = input.nextLine();

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

Expand All @@ -25,4 +26,25 @@ private static int wordCount(String s) {
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;

}

}
25 changes: 25 additions & 0 deletions Others/Palindrome.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,29 @@ public boolean SecondWay(String x) {

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;
}
}