Post

๐Ÿ’ก 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.