【LeetCode】 14. Longest Common Prefix 最长公共前缀(Easy)(JAVA)
题目地址: https://leetcode.com/problems/longest-common-prefix/
题目描述:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string “”.
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
题目大意
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
解题方法
直接循环遍历看当前字符的 i 为是否都相同即可
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
for (int i = 0; i < strs[0].length(); i++) {
char temp = strs[0].charAt(i);
for (int j = 0; j < strs.length; j++) {
if (i >= strs[j].length() || strs[j].charAt(i) != temp) {
if (i == 0) return "";
return strs[0].substring(0, i);
}
}
}
return strs[0];
}
}
执行用时 : 1 ms , 在所有 Java 提交中击败了 82.15% 的用户
内存消耗 : 37.7 MB, 在所有 Java 提交中击败了 33.20% 的用户
来源:CSDN
作者:吴中乐
链接:https://blog.csdn.net/qq_16927853/article/details/104538224