Java code O(n*resultLength) by Han


  • 0
    H
    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            if( strs == null || strs.length == 0 || strs[0].length() == 0) return "";
            
            int result = -1;
            while( ++result < strs[0].length() )
            {
                char c = strs[0].charAt(result);
                for( int i = 1; i < strs.length; i++)
                {
                    if( strs[i].length() <= result || strs[i].charAt(result) != c )
                    {
                        result--;
                        return result >= 0 ? strs[0].substring(0, result + 1) : "";
                    }
                }
            }
            
            return strs[0];
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.