C# solution: iterate column first.


  • 0
    B
    public class Solution 
    {
        public string LongestCommonPrefix(string[] strs) 
        {
            if (strs.Length == 0) return "";
    
            var result = new StringBuilder();
    
            var firstWord = strs[0];
    
            for (int j = 0; j < firstWord.Length; j++)
            {
                for(int i = 1; i < strs.Length; i++)
                {
                    var curWord = strs[i];
    
                    if (j == curWord.Length) return result.ToString();
    
                    if (firstWord[j] != curWord[j])
                    {
                        return result.ToString();
                    }
                }
                result.Append(firstWord[j]);
            }
    
            return result.ToString();
        }
    }
    

Log in to reply
 

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