Leetcode 14. Longest Common Prefix

来源:互联网 发布:ubuntu 解压缩文件 编辑:程序博客网 时间:2024/06/07 23:54

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

首先找到字符数组中最短的字符长度,然后取第一个字符串,开始从第一个字符开始遍历,如果遇到一个字符不统一,就返回从0到那个字符位置的字符串作为结果

public class Solution {    public String longestCommonPrefix(String[] strs) {      int length = strs.length;      // int[] strLength = new int[length];      String resultString = new String();      if (length == 0)        return resultString;      int mini = Integer.MAX_VALUE;      for(int i = 0 ; i < length; i++){        int tem = strs[i].length();        if(tem < mini)          mini = tem;      }      int result = mini;      for(int i = 0; i < mini; i++){        char tem = strs[0].charAt(i);        for(int j = 1; j < length; j++){          if(strs[j].charAt(i) != tem)            return strs[0].substring(0,i);        }      }      return strs[0].substring(0,mini);    }}



0 0
原创粉丝点击