Skip to content

Latest commit

 

History

History
50 lines (37 loc) · 1.15 KB

_14. Longest Common Prefix.md

File metadata and controls

50 lines (37 loc) · 1.15 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : May 22, 2024

Last updated : July 01, 2024


Related Topics : String, Trie

Acceptance Rate : 44.4 %


Solutions

Java

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 1) {
            return strs[0];
        }

        int shortestLen = strs[0].length();
        for (int i = 0; i < strs.length; i++) {
            shortestLen = Math.min(strs[i].length(), shortestLen);
        }

        for (int i = 0; i < shortestLen; i++) {
            for (int j = 1; j < strs.length; j++) {
                if (strs[j].charAt(i) != strs[j - 1].charAt(i)) {
                    return strs[0].substring(0,i);
                }
            }
        }

        return strs[0].substring(0, shortestLen);
    }
}