标签:leetcode
Write a function to find the longest common prefix string amongst an array of strings.
题目解析:写一个函数找出字符串数组的最长公共前缀,比如输入,String[] strs = { "aac", "aacab", "aac", "aabba", "aa" }输出 aa
解法:比较简单,属于leetcode easy级别的使用到substring(start,end),要注意该函数是左闭右开即只能取到【start,end-1】,上AC代码
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
原文地址:http://blog.csdn.net/xsf50717/article/details/47374785