Leetcode || Longest Common Prefix

来源:互联网 发布:讨厌知乎 编辑:程序博客网 时间:2024/05/21 04:24

Write a function to find the longest common prefix string amongst an array of strings.

Subscribe to see which companies asked this question

class Solution {        public String longestCommonPrefix(String[] strs) {            if(strs.length == 0)                    return "";            if(strs.length == 1)                    return strs[0];            int min_len = strs[0].length();            for(String str : strs) {                    if(str == "")                            return "";                    if(str.length()<min_len)                            min_len = str.length();            }            int k = 0;            String result = "";            boolean same = true;            for(int i=0; i<min_len && same; i++) {                    for(int j=0; j<strs.length-1; j++) {                            if(strs[j].charAt(i) !=  strs[j+1].charAt(i)) {                                    same = false;                                    break;                            }                    }                    if(same)                            result += strs[0].charAt(i);            }            return result;        }}
0 0