【LeetCode】14.Longest Common Prefix(Easy)解题报告

来源:互联网 发布:淘宝男装模特红人 编辑:程序博客网 时间:2024/06/06 05:43

【LeetCode】14.Longest Common Prefix(Easy)解题报告

tags:String

题目地址:https://leetcode.com/problems/longest-common-prefix/description/
题目描述:

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

  找出字符串序列中重复的字符串。提交了好几次,因为越界问题,要提前取到最小长度就可以了。还有不要忘异常判断。
Solutions:

class Solution {    public String longestCommonPrefix(String[] strs) {        if(strs.length==0){            return "";        }        int len=strs[0].length();        for(int i=0;i<strs.length;i++){            len=Math.min(strs[i].length(),len);        }        for(int i=0;i<strs.length-1;i++){            for(int j=0;j<len;j++){                if(strs[i].charAt(j)!=strs[i+1].charAt(j)){                    len=j;                }            }        }        return strs[0].substring(0,len);    }}

Date:2017年12月19日

阅读全文
0 0
原创粉丝点击