Social Icons

Wednesday, April 7, 2010

gHappy : Solutions for Javabat :05


For my previous solutions refer to this section.

Again it is a String question , it is as follows

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.

gHappy("xxggxx") → true
gHappy("xxgxx") → false
gHappy("xxggyygxx") → false

Actually what i did here was at loop through the string until a ‘g’ is found then check adjacent character to see whether it is a “g”s too. we have to check the whole string to see whether all the gs are happy.

  1: public boolean gHappy(String str) {
  2:   if(str.length()==0) return true;
  3:   if(str.length()<2) return false;
  4: 
  5:         boolean b=false;
  6:         for(int i=0; i<str.lastIndexOf("g");i++){
  7:             i=str.indexOf("g", i);
  8:             if(i!=str.length()-1 && str.charAt(++i)=='g') b=true;
  9:             else b=false;
 10:         }
 11:         return b;
 12: }
 
 
Blogger Templates http://slots.to/