题解 | #最长公共前缀#
最长公共前缀
https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
import java.util.*; public class Solution { /** * * @param strs string字符串一维数组 * @return string字符串 */ public String longestCommonPrefix (String[] strs) { // write code here if (strs == null || strs.length == 0) return ""; String model = strs[0]; StringBuilder builder = new StringBuilder(); char[] modelChars = model.toCharArray(); for (int i = 0; i < modelChars.length; i++) { char charAt = modelChars[i]; for (int j = 0; j < strs.length; j++) { try { char charTemp = strs[j].charAt(i); } catch (Exception e) { return builder.toString(); } if (!(strs[j].charAt(i) == charAt)) { return builder.toString(); } } builder.append(charAt); } return builder.toString(); } }
即使在算法中,也是可以配合异常来解决问题的