String related problem from CodingBat 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 &amp;&amp; str.charAt(0) == 'g') return false; 
   if(str.length() == 0) return true;

   for(int i = 1; i &lt; str.length() - 1; i ++) {
     if(str.charAt(i) == 'g') {
       if(str.charAt(i - 1) != 'g' &amp;&amp; str.charAt(i + 1) != 'g') return false;     
     } 
   }
 // edge cases (start-end)
 if(str.charAt(0) == 'g' &amp;&amp; str.charAt(1) != 'g') return false;
 if(str.charAt(str.length() - 1) == 'g' &amp;&amp; str.charAt(str.length() - 2) != 'g') return false;

 return true;
}
There's several 'special cases' in your code.


String of length 1
String of length 0
'g' at start of String
'g' at end of String


I'd recommend getting rid of these special cases.

To do this, you can check for special conditions inside the for-loop.

Loop through all the positions in the string, and check if there is a 'g' on that position. If it is, then check if the position is more than 0 (i.e. it has a char in front of it) or if the position is less than str.length - 1 (i.e. it has a char after it).

The details about how to write this can be done in oh so many ways, but here is what I would end up with:

for (int i = 0; i &lt; str.length(); i++) {
    char ch = str.charAt(i);
    if (ch == 'g') {
        if (i &gt; 0 &amp;&amp; str.charAt(i - 1) == ch) {
            continue;
        }
        if (i &lt; str.length() - 1 &amp;&amp; str.charAt(i + 1) == ch) {
            continue;
        }
        return false;
    }
}

return true;