【Leetcode】14. Longest Common Prefix

来源:互联网 发布:mac屏幕竖条一回消失 编辑:程序博客网 时间:2024/06/05 09:23

思路:

(1)注意判断空数组的情况。

(2)定义result记录当前最长前缀子串,初始为strs[0]。

(3)从strs[1]开始遍历数组,依次求strs[i]与result的前缀子串。

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

Runtime:14ms

1 0
原创粉丝点击