Social Icons

Tuesday, April 27, 2010

maxMirror: Solutions for Javabat:14


Question:

Say that a "mirror" section in an array is a group of contiguous elements such that somewhere in the array, the same group appears in reverse order. For example, the largest mirror section in {1, 2, 3, 8, 9, 3, 2, 1} is length 3 (the {1, 2, 3} part). Return the size of the largest mirror section found in the given array.

maxMirror({1, 2, 3, 8, 9, 3, 2, 1}) → 3
maxMirror({1, 2, 1, 4}) → 3
maxMirror({7, 1, 2, 9, 7, 2, 1}) → 2

Source

My Solution:

public int maxMirror(int[] nums) {
 int maxMirror=0 , mirrorCount=0;
            int len=nums.length;
            if(len<2) return len;
            for(int i=0 , j=len , k=0 , l=0 ; i<len-1 ; i++){
                // look for the currentvalue in the array
                while(--j>i && nums[j]!=nums[i]);
                if(j==i){ // no mirror starts from this val! check the next val
                    j=len-1; // next search must start from the end
                    continue;
                }
                else{ // found a mirror
                    k=i; // store boundaries of the mirror
                    l=j;
                    mirrorCount++;
                                        
                    while( (++k <= l && --j >= i) && (nums[k] == nums[j])  )
                        mirrorCount++;
                    if(mirrorCount > maxMirror)
                        maxMirror=mirrorCount;
                  
                    k=0 ; j=len; mirrorCount=0;
                }
            }// end for
            return maxMirror;
}

Comment (1)

Loading... Logging you in...
  • Logged in as
public int maxMirror(int[] nums) {
int width=1;
int max=0;
int comas=0;
String whole="";
String str="";

for(int i=0;i<nums.length;i++){

whole=whole+nums[i]+",";

}
while(width<nums.length+1){

for(int i=0;i<nums.length-width+1;i++){
str="";

for(int j=i;j<(i+width);j++){

str=nums[j]+","+str;

}

if(whole.contains(str) ){
comas=0;
for(int k=0;k<str.length();k++){
if(str.charAt(k)==',')
comas++;

}
if(max<comas)
max=comas;

}
}
width++;
}

return max;
}

Post a new comment

Comments by

 
 
Blogger Templates http://slots.to/