Leetcode 简单

LeetCode Simple_14 最长公共前缀

2020-01-01  本文已影响0人  天才一般的幼稚

问题描述

编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。

示例

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

思路

先获得最短字符串长度,依次比较,返回最长公共前缀。

class Solution {
    public String longestCommonPrefix(String[] strs) {
        int len = 0, index = 0, flag = 0;
        String minStr = "", commonPrefix = "";
        if(strs.length == 0){
            return "";
        }
        len = strs[0].length();
        minStr = strs[0];
        for(int i=1; i<strs.length; i++){
            if(strs[i].length() < len){
                len = strs[i].length();
                minStr = strs[i];
            }
        }
        while(index < len){
            flag = 0;
            for(int j=0; j<strs.length-1; j++){
                if(strs[j].charAt(index) == strs[j+1].charAt(index)){
                    continue;
                }else {
                    flag = 1;
                    break;
                }
            }
            if(flag == 0){
                commonPrefix += minStr.charAt(index);
            } else {
                break;
            }
            index ++;
        }
        return commonPrefix;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读