[14]. Longest common prefix

Longest common prefix

 


topic

Write a function to find the longest common prefix in a string array.

If there is no public prefix, the empty string "" is returned.

Example 1:

输入: ["flower","flow","flight"]
输出: "fl"

Example 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀

Explanation:

  • All input contains only lowercase letters az.
     

Function prototype

C function prototype:

char * longestCommonPrefix(char ** strs, int strsSize){}

 


Boundary judgment

if( strs == NULL || strsSize == 0)
        return "";
if(strsSize == 1)
        return strs[0];

 


Algorithm design: vertical scanning

Idea: Do a traversal, starting with the first word, define a pointer offset back, if the pointer offset process is different, return, otherwise it will continue to traverse.

for(int index=0; index<strlen(strs[0]); index++)       // 以第一个单词的长度做结束条件
    {
        char tmp = strs[0][index];             // 记录第一个单词的第 index 个字母, 与后面的字母比较
        for(int j=1; j<strsSize; j++){         // 和其它单词比较,不用和自己比了,所以从 1 开始
		    if( tmp != strs[j][index] || (!strs[j][index]) ){   // 其它单词的第 index 个字母不等于第一个单词第 index 个字母时、或者其它单词的字母已经被遍历完了
		       strs[0][index] = '\0';                       // 返回相同的前缀,但破坏了原数据不太好
               return strs[0];	 
            }  
	    }
    }
    return strs[0];   // 所有单词的所有字母都相等时,返回全部

Complete code:

char * longestCommonPrefix(char ** strs, int strsSize){
    if( strs == NULL || strsSize == 0)
        return "";
    if(strsSize == 1)
        return strs[0];

    for(int index=0; index<strlen(strs[0]); index++)       // 以第一个单词的长度做结束条件
    {
        char tmp = strs[0][index];             // 记录第一个单词的第 index 个字母, 与后面的字母比较
        for(int j=1; j<strsSize; j++){         // 和其它单词比较,不用和自己比了,所以从 1 开始
		    if( tmp != strs[j][index] || (!strs[j][index]) ){   // 其它单词的第 index 个字母不等于第一个单词第 index 个字母时、或者其它单词的字母已经被遍历完了
		       strs[0][index] = '\0';                       // 返回相同的前缀,但破坏了原数据不太好
               return strs[0];	 
            }  
	    }
    }
    return strs[0];       // 所有单词的所有字母都相等时,返回全部
}

Vertical scanning complexity:

  • time complexity: Θ ( n 2 ) \Theta(n^{2})
  • Space complexity: Θ ( 1 ) \Theta(1)
Published 132 original articles · praised 377 · 70,000 views

Guess you like

Origin blog.csdn.net/qq_41739364/article/details/105447255