Straight forward C# solution


  • 1
    H

    public class Solution {

    public string LongestCommonPrefix(string[] strs) {
        
        if(strs==null || strs.Length == 0) 
            return "";
            
        string res ="";
        for( int j = 0; j < strs[0].Length; j++){
            for( int i = 1; i < strs.Length; i++)
            {
                if( strs[i].Length < (j+1) || strs[i][j] != strs[0][j])
                    return res;
            }
            res+=strs[0][j];
        }
        
        return res;
        
    }
    

    }

    O(m*n) solution, assuming the there are m strings and their shortest length is n.
    Can this be optimized ?


Log in to reply
 

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