CodingBat: Java. String-3, Part II

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

3 thoughts on “CodingBat: Java. String-3, Part II

  1. Val

    I like your code to solve the corner cases. However, I am confused about corner cases. I was wondering when do I need to add your corner cases code? If I have a compiler available, then I will know to just check. If I’m at a white board for an interview, I will not know when to use your corner case code.

    Reply
    1. Gregor Ulm Post author

      A compiler won’t catch all corner cases, so I wouldn’t rely on that. The situation is a lot worse in C, though.

      I’d say it’s a good habit to consider corner cases. If you want to increase your level of confidence in the code you’re writing, then add some unit tests or, better, write properties for a tool like QuickCheck, which will generate test cases for you. The latter is incredibly powerful, and not often used in practice.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>