2015年9月17日星期四

Leetcode 14 Longest Common Prefix

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

Solution 1: easy coding.
 public class Solution {  
   public String longestCommonPrefix(String[] strs) {  
     int m=strs.length;  
     if (m==0) return "";  
     int n=strs[0].length();  
     StringBuilder res=new StringBuilder();  
     for (int i=0; i<n; i++) {  
       char c=strs[0].charAt(i);  
       for (int j=1; j<m; j++) {  
         if (i>=strs[j].length() || c!=strs[j].charAt(i)) return res.toString();  
       }  
       res.append(c);  
     }  
     return res.toString();  
   }  
 }  

没有评论:

发表评论