标签:
题目链接:https://leetcode.com/problems/longest-common-prefix/
题目:Write a function to find the longest common prefix string amongst an array of strings.
解题思路:寻找字符串数组的最长公共前缀,将数组的第一个元素作为默认公共前缀,依次与后面的元素进行比较,取其公共部分,比较结束后,剩下的就是该字符串数组的最长公共前缀,示例代码如下:
public class Solution { public String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) { return ""; } String prefix = strs[0]; for (int i = 1; i < strs.length; i++) { int j = 0; while (j < strs[i].length() && j < prefix.length() && strs[i].charAt(j) == prefix.charAt(j)) { j++; } if (j == 0) { return ""; } prefix = prefix.substring(0, j); } return prefix; } }
【LeetCode OJ 14】Longest Common Prefix
标签:
原文地址:http://blog.csdn.net/xujian_2014/article/details/50725804