CodingBat: Java. Warmup-2, Part II


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


Here is the second part of the solutions to Warmup-2:

stringMatch:

public int stringMatch(String a, String b) {
		int count = 0;
		int minLength = Math.min(a.length(), b.length());
		for (int i = 0; i < minLength - 1; i++) {
			if (a.substring(i, i + 2).equals(b.substring(i, i + 2)))
				count++;
		}
		return count;
}

stringX:

public String stringX(String str) {
		String result = "";
		if (str.length() <= 2) return str;
		
		result += str.charAt(0);
		for (int i = 1; i < str.length() - 1; i++) {
			if (str.charAt(i) != 'x') result += str.charAt(i);
		}
		result += str.charAt(str.length() - 1);
		return result;
}

altPairs:

public String altPairs(String str) {
		String result = "";
		for (int i = 0; i < str.length(); i += 4) {
			result += str.charAt(i);
			if (i + 1 < str.length())
				result += str.charAt(i + 1);
		}
		return result;
}

stringYak:

public String stringYak(String str) {
		int posYak = str.indexOf("yak");
		while (posYak != -1) {
			str = str.substring(0, posYak) + str.substring(posYak + 3);
			posYak = str.indexOf("yak");
		}
		return str;
  }

There is a mistake in the description on the website, which says “Given a string, return a version where all the “yak” are removed, but the “a” can be any char.” All test cases use “yak”, though, which simplifies the solution.

Also, please note that the purpose of exercises such as this one is to familiarize yourself with loops. Using str.replace() would completely defeat this purpose.

array667:

public int array667(int[] nums) {
		int count = 0;
		for (int i = 0; i < nums.length - 1; i++)
			if (nums[i] == 6 && (nums[i + 1] == 6 || nums[i + 1] == 7))
				count++;
		return count;
}

noTriples:

public boolean noTriples(int[] nums) {
		for (int i = 0; i < nums.length - 2; i++)
			if (nums[i] == nums[i + 1] && nums[i + 1] == nums[i + 2])
				return false;
		return true;
}

has271:

public boolean has271(int[] nums) {
		for (int i = 0; i < nums.length - 2; i++)
			if (nums[i] == nums[i + 1] - 5
					&& (Math.abs((nums[i + 2] + 1) - nums[i]) <= 2))
				return true;
		return false;
}

For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


One thought on “CodingBat: Java. Warmup-2, Part II

Leave a Reply

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

Spammer prevention; the answer is an integer: * Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.