Saturday, January 10, 2015

Longest Common Prefix (LeetCode String)

Question:Write a function to find the longest common prefix string amongst an array of strings.

Idea: Brute force. Use the first string as the template for comparison. The compare the characters of each string one by one with the first string, if any mismatch happens, return the last valid length.

Time: O(n^2) Space: O(1)

Code:
 public class Solution {  
   public String longestCommonPrefix(String[] strs) {  
     if(strs.length==0)  
       return "";  
     String first=strs[0];  
     int rightMost=first.length()-1;  
     for(int i=0;i<strs.length;i++)  
     {  
       for(int j=0;j<=rightMost;j++)  
       {  
         if(j>strs[i].length()-1||strs[i].charAt(j)!=first.charAt(j))  
           rightMost=j-1;  
       }  
     }  
     return rightMost>=0?first.substring(0,rightMost+1):"";  
   }  
 }  

No comments:

Post a Comment