Exes and Ohs in Java

The challenge

Check to see if a string has the same amount of ‘x’s and ‘o’s. The method must return a boolean and be case insensitive. The string can contain any char.

Examples input/output:

XO("ooxx") => true XO("xooxx") => false XO("ooxXm") => true XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true XO("zzoo") => false
Code language: PHP (php)

The solution in Java code

Option 1:

import java.util.*; public class XO { public static boolean getXO (String str) { Map<String, Integer> m = new HashMap<>(); m.put("x", 0); m.put("o", 0); for (int i = 0; i < str.length(); i++){ char c = str.charAt(i); if (Character.toLowerCase(c)=='x') m.put("x", m.get("x")+1); if (Character.toLowerCase(c)=='o') m.put("o", m.get("o")+1); } return m.get("x")==m.get("o"); } }
Code language: Java (java)

Option 2:

public class XO { public static boolean getXO (String str) { str = str.toLowerCase(); return str.replace("o","").length() == str.replace("x","").length(); } }
Code language: Java (java)

Option 3:

public class XO { public static boolean getXO (String str) { String xValues = str.replaceAll("[^xX]", ""); String oValues = str.replaceAll("[^oO]", ""); return xValues.length() == oValues.length(); } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testSomething1() { assertEquals(true, XO.getXO("xxxooo")); } @Test public void testSomething2() { assertEquals(true, XO.getXO("xxxXooOo")); } @Test public void testSomething3() { assertEquals(false, XO.getXO("xxx23424esdsfvxXXOOooo")); } @Test public void testSomething4() { assertEquals(false, XO.getXO("xXxxoewrcoOoo")); } @Test public void testSomething5() { assertEquals(false, XO.getXO("XxxxooO")); } @Test public void testSomething6() { assertEquals(true, XO.getXO("zssddd")); } @Test public void testSomething7() { assertEquals(false, XO.getXO("Xxxxertr34")); } }
Code language: Java (java)
Notify of
Inline Feedbacks
View all comments