Note: A run is a series of adjacent chars that are the same.
I just want to answer a few questions:
- Is this readable?
- Does it need commenting or is it self-descriptive enough?
- Are there any efficiency tweaks this could have?
- Is this a good way to test?
- Which is the preferred/conventional syntax?
int maxCheck = 0,
maxRun = 1,
currentRun = 1;`
vs.
int maxCheck = 0, maxRun = 1, currentRun = 1;
vs.
int maxCheck = 0;
int maxRun = 1,
int currentRun = 1;
I surmise this probably varies from individual to individual, but for this challenge in particular my instincts were to exclude spaces, but the challenge didn't specify this, and in the last challenge: my intuition, just as the first answer, also wanted me to include digits larger than 9, but that was actually 'wrong' and outside of the specifications of the challenge -- as was evidenced with failed tests (provided by the challenge).
Should I just take 'requirements' literally most of the time to avoid constructing technically 'incorrect' code? I ask since the tests in this case don't include spaces, and it's definitely something I'm wondering in case of larger, more abstract projects.
public class Standford2 {
public static void main(String[] args) {
System.out.println("Test 1: " + (1 == maxRun("123")));
System.out.println("Test 2: " + (2 == maxRun("1223")));
System.out.println("Test 3: " + (2 == maxRun("112233")));
System.out.println("Test 4: " + (3 == maxRun("1112233")));
System.out.println("Test 5: " + (2 == maxRun("hoopla")));
System.out.println("Test 6: " + (3 == maxRun("hoopllla")));
System.out.println("Test 7: " + (3 == maxRun("abbcccddbbbxx")));
System.out.println("Test 8: " + (0 == maxRun("")));
System.out.println("Test 9: " + (3 == maxRun("hhhooppoo")));
}
public static int maxRun(String str) {
if (str.length() == 0) { return 0; }
int maxCheck = 0,
maxRun = 1,
currentRun = 1;
if (str.length() == 1) { return maxRun; }
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i) == str.charAt(i - 1)) {
currentRun++;
if (currentRun > maxRun) { maxRun = currentRun; }
}
else { currentRun = 1; }
}
return maxRun;
}
}