Problem 14

longest Common Prefix

Posted by Ruizhi Ma on December 1, 2019

问题描述

https://leetcode.com/problems/longest-common-prefix/

解决思路

将第一个字符串整体拿来和剩下的所有字符串比较,如果不等,则第一个字符串从后往前减少一位;若相等,则返回字符。

问题解惑

indexOf的用法:在这个地方,strs[i].indexOf(prefix)的意思是,从头开始查找是否包含prefix的字符串。
当然indexOf还可以指定查找下标的其他用法,百度或者google去吧~
这题没什么参考价值。。。下次不做了

代码(2019-12-01)

class Solution {
    public String longestCommonPrefix(String[] strs) {
        //corner case
        if(strs.length == 0 || strs == null) return "";
        
        String prefix = strs[0];
        
        for(int i = 1; i < strs.length; i++){
            //if the prefix is not common, shorten it from the end
            while(strs[i].indexOf(prefix) != 0){
                prefix = prefix.substring(0, prefix.length() - 1);
            }
        }
        
        return prefix;
    }
}

复杂度分析:

时间复杂度: O(n)
空间复杂度: O(n)