[Problem]
Write a function to find the longest common prefix string amongst an array of strings.
[Analysis]
思路非常简单,循环验证每一个字符串就可以通过OJ,代码也没有优化。
[Solution]
public class Solution { public String longestCommonPrefix(String[] strs) { if (strs.length == 0) { return ""; } if (strs.length == 1) { return strs[0]; } int idx = 0; boolean flag = true; while (idx < strs[0].length()) { char c = strs[0].charAt(idx); for (int i = 1; i < strs.length; i++) { if (idx >= strs[i].length() || strs[i].charAt(idx) != c) { flag = false; break; } } if (flag) { idx++; } else { break; } } return strs[0].substring(0, idx); } }
时间: 2024-10-13 12:17:02