链接:https://leetcode-cn.com/problems/longest-common-prefix/solution/zui-chang-gong-gong-qian-zhui-1-by-flagmain/
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1: 输入: ["flower","flow","flight"]. 输出: "fl"
示例 2: 输入: ["dog","racecar","car"]. 输出: ""
解释: 输入不存在公共前缀。
解题思路
思路 1:遍历字母 ,慢。。。
1. 标记第一个单词 和 第一个字母位置
2. while 获取字母,如果是第一个单词就保存下字母 否则对比是否与第一次记录的字母相同
3. 是否最后一个单词,是则单词重新从0开始,并检查第二个字符
4. 最后输出公共前缀字符
Java:
class Solution {
public String longestCommonPrefix(String[] strs) {
String res = "";
// 标记第一个单词 和 第一个字母位置
int length = strs.length, word = 0, letter = 0;
if( length == 0 || strs[word].length() == 0 ) return res;
char contrast = strs[0].charAt(0);
while( word < length && letter < strs[word].length() ) {
// 获取字母,如果是第一个单词就保存下 否则对比是否与第一个单词字母相同
char tmp = strs[word].charAt(letter);
if( word == 0 ){
contrast = tmp;
}else{
// 与第一个单词不相同 break。
if( contrast != tmp ) break;
}
// 是否最后一个单词,继续
if( word < length - 1 ){
System.out.println(word);
word++;
continue;
}
// 单词重新从0开始,并检查第二个字符
res += tmp;
letter++;
word = 0;
}
return res;
}
}
Python:
class Solution(object):
def longestCommonPrefix(self, strs):
res = ''
# 标记第一个单词 和 第一个字母位置
word = letter = 0
length = len(strs)
while word < length and letter < len(strs[word]):
tmp = strs[word][letter]
# 获取字母,如果是第一个单词就保存下 否则对比是否与第一个单词字母相同
if word == 0:
contrast = tmp
else:
if strs[word][letter] != contrast: break
# 是否最后一个单词,继续
if word < length - 1:
word += 1
continue;
# 单词重新从0开始,并检查第二个字符
res += tmp;
letter += 1;
word = 0;
return res