Saturday, July 16, 2022

14. Longest Common Prefix

[TODO] Version #2 Binary Search


一刷 07/2022

Version #1 Iteration

用了一个while true取代了先把所有str iteration一遍然后去min的过程

Time O(MN)

Space O(1)

Runtime: 1 ms, faster than 88.54% of Java online submissions for Longest Common Prefix.
Memory Usage: 40.1 MB, less than 96.22% of Java online submissions for Longest Common Prefix.

class Solution {

    public String longestCommonPrefix(String[] strs) {

        StringBuilder sb = new StringBuilder();

        int i = 0;

        while (true) {

            Character c = null;

            for (String str : strs) {

                if (i >= str.length()) {

                   return sb.toString();

                }

                if (c != null && str.charAt(i) != c) {

                    return sb.toString();

                }

                if (c == null) {

                    c = str.charAt(i);

                }

            }

            sb.append(c);

            i++;

        }

    }

}

No comments:

Post a Comment