C# easy to understand solution


  • 0
    S
    public string LongestCommonPrefix(string[] strs) {
        if (strs.Length == 0) {
            return "";
        }
        
    	string commonBeginning = "";
    	int maxLength = Int32.MaxValue;
    
    	foreach (string s in strs) {
    		if (s.Length < maxLength) {
    			maxLength = s.Length;
    		}
    	}
    	for (int i = 0; i < maxLength; i++) {
    
    		string possibleCommonBeg = commonBeginning + strs[0][i];
    		foreach (string s in strs) {
    			if (!s.StartsWith(possibleCommonBeg)) {
    				return commonBeginning;
    			}
    		}
    		commonBeginning = possibleCommonBeg;
    	}
    	return commonBeginning;
    }

Log in to reply
 

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