File tree 2 files changed +47
-0
lines changed
2 files changed +47
-0
lines changed Original file line number Diff line number Diff line change @@ -16,6 +16,7 @@ public static void main(String[] args) {
16
16
String str = input .nextLine ();
17
17
18
18
System .out .println ("Your text has " + wordCount (str ) + " word(s)" );
19
+ System .out .println ("Your text has " + secondaryWordCount (str ) + " word(s)" );
19
20
input .close ();
20
21
}
21
22
@@ -25,4 +26,25 @@ private static int wordCount(String s) {
25
26
return s .trim ().split ("[\\ s]+" ).length ;
26
27
}
27
28
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
+
28
50
}
Original file line number Diff line number Diff line change @@ -22,4 +22,29 @@ public boolean SecondWay(String x) {
22
22
23
23
return SecondWay (x .substring (1 , x .length () - 1 ));
24
24
}
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
+ }
25
50
}
You can’t perform that action at this time.
0 commit comments