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

9 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
  2. Charlie

    Regarding the “notReplace” answer, could you please explain why your answer does not leave off the last character in the given string? For example, if you have the string “abcde” and add a space at the beginning and end (per your answer), you have a string length of 7. The loop only continues if “i” is less than 7-2(i.e., 5), which would correspond to stopping at letter “d”. I must be missing something.

    Thanks,

    Reply
    1. Gregor Ulm Post author

      Charlie, I’m not adding one space character at the end of the string, but two. I hope this clears up your confusion.

      Reply
  3. Chris

    I am a bloody beginner in Java, but I tried solving the ‘maxBlock’ function with only one loop. Just thought I’d share, since you previously emphasized that the String-3 instructions (use 2 loops) baffled you and you showed that most stuff can be done with one loop.

    I am not saying this is nicer or whatever, just that has one less loop.

    Link: http://pastebin.com/3mEzGe2M

    Reply
  4. Earl

    A question about mirrorEnds – could you explain why this code:
    for(int i=0; i=0; j–)
    instead of
    for (int i = 0, j = len – 1; i < len; i++, j–)
    doesn't work? To me it looks like it does the same, but the results are different.

    Reply
  5. Earl

    The code is not showing correctly, what I meant was
    for(int i=0; i is less than len; i plus plus) and then another loop: for(int j=len-1; j is greater or equal to 0; j minus minus).

    Reply
    1. Gregor Ulm Post author

      The code I’ve written uses one loop. It’s beyond me why your code, which uses a nested for-loop, “looks like it does the same”. Are you sure you understand how a loop inside a loop is evaluated?

      Reply

Leave a Reply

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


five × 8 =

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>