For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.
sameEnds:
public String sameEnds(String string) { String result = ""; int len = string.length(); for (int i = 0; i <= len / 2; i++) for (int j = len / 2; j < len; j++) if (string.substring(0, i).equals(string.substring(j))) result = string.substring(0, i); return result; }
The variable in line 3 makes the code a bit more compact.
mirrorEnds:
public String mirrorEnds(String string) { String result = ""; int len = string.length(); for (int i = 0, j = len - 1; i < len; i++, j--) if (string.charAt(i) == string.charAt(j)) result += string.charAt(i); else break; return result; }
maxBlock:
public int maxBlock(String str) { int max = 0; for (int i = 0; i < str.length(); i++) { int count = 0; for (int j = i; j < str.length(); j++) { if (str.charAt(i) == str.charAt(j)) count++; else break; } if (count > max) max = count; } return max; }
sumNumbers:
public int sumNumbers(String str) { int sum = 0; for (int i = 0; i < str.length(); i++) { if (Character.isDigit(str.charAt(i))) { int count = 0; for (int j = i; j < str.length(); j++) { if (Character.isDigit(str.charAt(j))) count++; else break; } sum += Integer.parseInt(str.substring(i, i + count)); i += count; } } return sum; }
notReplace:
public String notReplace(String str) { String result = ""; str = " " + str + " "; // avoid issues with corner cases for (int i = 0; i < str.length() - 2; i++) { if (str.charAt(i) == 'i') { if (str.charAt(i + 1) == 's' && !Character.isLetter(str.charAt(i + 2)) && !Character.isLetter(str.charAt(i - 1))) { result += "is not"; i += 1; } else result += "i"; } else result += str.charAt(i); } return result.substring(1); }
For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.