From a4156fcb7aaf0fe167e74463884b499013480184 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Furaha=20Dami=C3=A9n?= Date: Tue, 27 Aug 2019 21:49:33 -0400 Subject: [PATCH 1/2] ignore non-alphanumeric --- Others/Palindrome.java | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Others/Palindrome.java b/Others/Palindrome.java index 28e9b5e38..af4a72fde 100644 --- a/Others/Palindrome.java +++ b/Others/Palindrome.java @@ -22,4 +22,29 @@ class Palindrome { 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; + } } From 4ddbaca62e27d4b530211cd01b915cd6678cdd3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Furaha=20Dami=C3=A9n?= Date: Tue, 27 Aug 2019 22:01:09 -0400 Subject: [PATCH 2/2] secondaryWordCount method added --- Others/CountWords.java | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Others/CountWords.java b/Others/CountWords.java index c3e0ddf1e..5dc637559 100644 --- a/Others/CountWords.java +++ b/Others/CountWords.java @@ -16,6 +16,7 @@ public class CountWords { 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(); } @@ -25,4 +26,25 @@ public class CountWords { 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; + + } + }