[Algorithm] Leetcode_Longest Common Prefix

JAsmine_log·2024년 5월 15일
0

Longest Common Prefix

Problem

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<=2001 <= strs.length <= 200
0<=strs[i].length<=2000 <= strs[i].length <= 200
strs[i]strs[i] consists of only lowercase English letters.

Soluions & Aanlysis

prefix = 단어 맨 처음에 오는 고정 문자열
중간에 오는 것은 체크되지 않는다

Code

Java1

//https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/887/
class Solution {
    public String longestCommonPrefix(String[] strs) {
		Integer size = Integer.MAX_VALUE;
        String temp = "";
        for (String str : strs) {
            if (size > str.length()) {
                size = str.length();
                temp = str;
            }
        }

        String prefix = "";
        int isChecked = 0;
        String minPrefix = "";
        for (int i = 0; i < size; i++) {
            isChecked = 0;
            prefix += Character.toString(temp.charAt(i));

            for (String str : strs) {
                if (str.indexOf(prefix) == 0) {
                    isChecked++;

                    if (isChecked == strs.length)
                        minPrefix = prefix;
                } else
                    break;
            }
        }
        return minPrefix;
}

Java2

//https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/887/
class Solution {
    public String longestCommonPrefix(String[] strs) {
    String str = strs[0];

        if (strs.length == 1) {
            return str;
        }

        for (int i = 0; i < str.length(); i++) {
            if (!check(strs, str.charAt(i), i))
                return str.substring(0, i);
        }

        return str;
    }

	private boolean check(String[] strs, char c, int index) {
        for (String str : strs) {
            if (str.length() <= index)
                return false;

            if (c != str.charAt(index))
                return false;
        }

        return true;
    }
}

Extra Testcase

Exampel3 = {"dog", "racedog", "car"}

profile
Everyday Research & Development

0개의 댓글