For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.
When I began working on the String-3 section of CodingBat, I felt mislead by the description, which said “Harder String problems — 2 loops.” However, most problems can be solved by only using one loop. The difficulty of the exercises is quite uneven, so don’t get frustrated if some take considerably more time than others.
All solutions were successfully tested on 23 February 2013.
countYZ:
public int countYZ(String str) { int count = 0; str = str.toLowerCase() + " "; for (int i = 0; i < str.length() - 1; i++) if ((str.charAt(i) == 'y' || str.charAt(i) == 'z') && !Character.isLetter(str.charAt(i + 1))) count++; return count; }
The string manipulation in line 3 takes care of the edge case where the last letter in the string is checked. In my opinion, this is cleaner than adding an extra condition in the for loop.
withoutString:
public String withoutString(String base, String remove) { String result = ""; int index = base.toLowerCase().indexOf(remove.toLowerCase()); while (index != -1) { result += base.substring(0, index); base = base.substring(index + remove.length()); index = base.toLowerCase().indexOf(remove.toLowerCase()); } result += base; return result; }
equalIsNot:
public boolean equalIsNot(String str) { int countIs = 0; int countNot = 0; str = str + "X"; for (int i = 0; i < str.length() - 2; i++) { if (str.substring(i, i + 2).equals("is")) countIs++; if (str.substring(i, i + 3).equals("not")) countNot++; } return (countIs == countNot); }
The string manipulation in line 4 avoids a second for loop. By lengthening the string by a character that is not in “is” or “not”, it’s possible to do all necessary checks in just one pass.
gHappy:
public boolean gHappy(String str) { str = "X" + str + "X"; // for corner cases for (int i = 1; i < str.length() - 1; i++) if (str.charAt(i) == 'g' && str.charAt(i - 1) != 'g' && str.charAt(i + 1) != 'g') return false; return true; }
countTriple:
public int countTriple(String str) { int count = 0; for (int i = 0; i < str.length() - 2; i++) if (str.charAt(i) == str.charAt(i + 1) && str.charAt(i + 1) == str.charAt(i + 2)) count++; return count; }
sumDigits:
public int sumDigits(String str) { int sum = 0; for (int i = 0; i < str.length(); i++) if (Character.isDigit(str.charAt(i))) sum += Integer.parseInt(str.substring(i, i + 1)); return sum; }
For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.