14. Longest Common Prefix 发表于 2022-07-03 1234567891011121314151617181920class Solution { public String longestCommonPrefix(String[] strs) { int endIndex = 0; // exclusive String sentinel = strs[0]; while (endIndex < sentinel.length()) { for (int i = 1; i < strs.length; i++) { String str = strs[i]; if (endIndex == str.length() || str.charAt(endIndex) != sentinel.charAt(endIndex)) { // 无法到达 endIndex 或 endIndex 上的字符不相等 // 注意此处不能使用 break, 因为 break 只能跳出一层 return sentinel.substring(0, endIndex); } } endIndex++; } return sentinel.substring(0, endIndex); }} Reference14. Longest Common Prefix