๐ก LeetCode 14 - Longest Common Prefix
๐ก LeetCode 14 - 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 โโ.
์ ์ถ๋ ฅ ์์
โ ์์ 1
1
2
Input: strs = ["flower","flow","flight"]
Output: "fl"
โ ์์ 2
1
2
3
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
์ ์ฝ์กฐ๊ฑด
1 <= strs.length <= 200
0 <= strs[i].length <= 200
- strs[i] consists of only lowercase English letters if it is non-empty.
์์ฑ ์ฝ๋
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public String longestCommonPrefix(String[] strs) {
// 1. ๋ณ์ ์ ์ธ ๋ฐ ์ด๊ธฐํ
String result = "";
int shortestLength = 200;
StringBuilder sb = new StringBuilder();
// 2. ๋ฐฐ์ด ์์ ์ค ๋ฌธ์์ด ์ต์ ๊ธธ์ด ์ถ์ถ
for (String str : strs) {
int newStrLength = str.length();
if (str.length() < shortestLength) shortestLength = newStrLength;
}
// 3. ๊ฐ์ฅ ์งง์ ๋ฌธ์์ด ๋งํผ prefix ํ๋ณ
for (int i=0; i<shortestLength; i++) {
// ํ๋๊ทธ ๋ฐ ๋ฌธ์ ์ด๊ธฐํ
boolean prefixFlag = true;
char c = strs[0].charAt(i);
// ๋ฌธ์์ด ๋ฐฐ์ด ์ํํ๋ฉฐ ๋์ผ ์ฌ๋ถ ํ์ธ
for (int j=0; j<strs.length; j++) {
if (c != strs[j].charAt(i))ย prefixFlag = false;
}
// ํ๋๊ทธ๊ฐ ๊ฑฐ์ง์ด๋ผ๋ฉด ์ํ ํ์ถ
if (!prefixFlag) break;
// ํ๋๊ทธ๊ฐ ์ฐธ์ด๋ผ๋ฉด ๊ฒฐ๊ณผ์ ์ถ๊ฐ
sb.append(c);
}
// 4. ๋ฐํ
result = sb.toString();
return "".equals(result) ? "" : result;
}
}
- ๋ฌธ์์ด ๋ฐฐ์ด์์ ๊ฐ ๋ฌธ์์ด์ ๊ธธ์ด๊ฐ ๋ชจ๋ ๋ค๋ฅผ ๊ฒ์ด๋ค.
NullPointerException
์ ํผํ๊ธฐ ์ํด ๋ฌธ์์ด์ ์ต์ ๊ธธ์ด ๋งํผ๋ง ์ํํ๋ค.
๊ฐ์ ์ฝ๋
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.Arrays;
public class LongestCommonPrefix {
public static String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
Arrays.sort(strs);
String first = strs[0];
String last = strs[strs.length - 1];
int i = 0;
while (i < first.length() && i < last.length() && first.charAt(i) == last.charAt(i)) {
i++;
}
return first.substring(0, i);
}
public static void main(String[] args) {
String[] input = {"flower", "flow", "flight"};
System.out.println("๊ณตํต ์ ๋์ฌ: " + longestCommonPrefix(input));ย ย // ์ถ๋ ฅ: "fl"
}
}
- ์ด์ค
for
๋ฌธ์ ์์ ๊ณ ์ถ์ด์ChatGPT
์ ๋ฌผ์ด๋ดค๋๋ฐ, ์ฐธ์ ํ ์์ด๋์ด๊ฐ ์์๋ค.ย - ๋ฌธ์์ด ๋ฐฐ์ด์ ์ฌ์ ์์ผ๋ก ์ ๋ ฌํ๊ณ ์ฒซ ๋ฒ์งธ ๋ฌธ์์ด๊ณผ ๋ง์ง๋ง ๋ฌธ์์ด๋ง ํ์ธํ๋ ๊ฒ์ด๋ค.
This post is licensed under CC BY 4.0 by the author.