I was trying this problem and I was wondering if there is a way to check for the edge cases inside the for-loop.
The problem statement:
We'll say that a lowercase 'g' in a string is "happy" if there is another 'g' immediately to its left or right. Return true if all the g's in the given string are happy.
Here I am starting the loop from index 1 as I need to look back and I don't want an ArrayIndexOutOfBounds
exception. The same applies for the end edge case where I need to look the following index.
To avoid this problem I'm checking these cases right after I've checked all the others, but it doesn't feel quite right. Is there a way to do it in a more compact way?
public boolean gHappy(String str) {
if(str.length() == 1 && str.charAt(0) == 'g') return false;
if(str.length() == 0) return true;
for(int i = 1; i < str.length() - 1; i ++) {
if(str.charAt(i) == 'g') {
if(str.charAt(i - 1) != 'g' && str.charAt(i + 1) != 'g') return false;
}
}
// edge cases (start-end)
if(str.charAt(0) == 'g' && str.charAt(1) != 'g') return false;
if(str.charAt(str.length() - 1) == 'g' && str.charAt(str.length() - 2) != 'g') return false;
return true;
}