Post

[LeetCode 14] Longest Common Prefix

LeetCode 14 (Java)
[Longest Common Prefix] 문제 풀이

[LeetCode 14] Longest Common Prefix

문제 바로가기


Description


Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".


Example 1


  • Input: strs = [“flower”,”flow”,”flight”]
  • Output: “fl”


Example 2


  • Input: strs = [“dog”,”racecar”,”car”]
  • Output: “”
  • Explanation:
    • There is no common prefix among the input strings.


Constraints


  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters if it is non-empty.







Code


내 제출


1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
    public String longestCommonPrefix(String[] strs) {
        String result = strs[0];
        
        for(int i = 1; i < strs.length; i++){
            while(strs[i].indexOf(result) != 0){
                result = result.substring(0, result.length() - 1);
            }
        }
        return result;
    }
}


RuntimeMemory
0 ms42 MB


다른 풀이


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
    public String longestCommonPrefix(String[] v) {
        StringBuilder ans = new StringBuilder();
        Arrays.sort(v);
        String first = v[0];
        String last = v[v.length-1];
        for (int i=0; i<Math.min(first.length(), last.length()); i++) {
            if (first.charAt(i) != last.charAt(i)) {
                return ans.toString();
            }
            ans.append(first.charAt(i));
        }
        return ans.toString();
    }
}


Reference


This post is licensed under CC BY 4.0 by the author.