14. 最长公共前缀

image.png

题解

执行用时:1 ms, 在所有 Java 提交中击败了75.20%的用户 内存消耗:36.5 MB, 在所有 Java 提交中击败了63.64%的用户

  1. class Solution {
  2. public String longestCommonPrefix(String[] strs) {
  3. StringBuilder sb = new StringBuilder();
  4. int idx = 0;
  5. while (true) {
  6. char tempChar = ' ';
  7. for (String str : strs) {
  8. if (str.length() - 1 < idx) return sb.toString();
  9. if (tempChar == ' ') {
  10. tempChar = str.charAt(idx);
  11. } else if (tempChar != str.charAt(idx)) {
  12. return sb.toString();
  13. }
  14. }
  15. sb.append(tempChar);
  16. idx ++;
  17. }
  18. }
  19. }