leetcode 14. 最长公共前缀

链接: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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黑漆#000000

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值