【LeetCode OJ 14】Longest Common Prefix

来源:互联网 发布:淘宝虚拟物品货源 编辑:程序博客网 时间:2024/06/14 23:30

题目链接: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;}}


0 0
原创粉丝点击