─━ IT ━─

[릿코드, Leetcode] [JAVA] Longest Common Prefix

DKel 2021. 4. 1. 08:52
반응형
 

Longest Common Prefix - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Leetcode - Longest Common Prefix

설명

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:

Input: strs = ["flower","flow","flight"]

Output: "fl"

제한사항

 

  • 0 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lower-case English letters.

 

 

 

소스코드

class Solution {
    public String longestCommonPrefix(String[] strs) {
        
        String str = "";
        boolean isDone = false;
        if (strs.length > 0) {
            for (int i=0; i<strs[0].length(); i++) {
                char c = strs[0].charAt(i);
                str += String.valueOf(c);

                for (int j=1; j<strs.length; j++) {
                    if (!strs[j].startsWith(str)) {
                        isDone = true;
                        break;
                    }
                }

                if (isDone) {
                    str = str.substring(0, str.length() - 1);
                    break;
                }
            }
        }
        return str;
    }
}

제출한 소스코드

 

lemondkel - Overview

4-Year Web programmer. lemondkel has 41 repositories available. Follow their code on GitHub.

github.com

 

반응형