Mega Code Archive

 
Categories / Java / Data Type
 

Longest Starting Match

public class Util{   public static String longestStartingMatch(String source1, String source2)   {     /**      * I starting with the regex lookingAt() but it wasn't working for the test      * cases I had (comparison of BigDecimals... DaC seems to work ok.      */          int min = 0;     int max = source1.length();     int cur = max/2;     while(true)     {       if(source2.regionMatches(0, source1, 0, cur))       {         min = cur;         cur+= (max-cur)/2;         if(cur == min)         {           if(source2.regionMatches(0, source1, 0, max))             cur = max;           break;         }       }else{         max = cur;         cur-= (cur-min)/2;         if(cur == max)         {           if(source2.regionMatches(0, source1, 0, min))             cur = min;           break;         }       }     }     return source2.substring(0, cur);   } }