JAVA-알고리즘 Leetcode(Easy)-Longest Common Prefix
포스트
취소

JAVA-알고리즘 Leetcode(Easy)-Longest Common Prefix

Question

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
2
3
4
5
6
7
8
#1
Input: ["flower","flow","flight"]
Output: "fl"

#2
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Solution

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
public class LongestCommonPrefix {

	public static void main(String[] args) {
		// LeetCode Easy 14

		String[] s = {"apple", "application", "aplogise" , "api"};
		
		int len = s.length;
		
		String result = longestCommonPrefix(s, len);
		System.out.println(result);
		
	}
	
	public static String longestCommonPrefix(String[] s, int len) {
		String prefix = null;
		
		if(len == 0) {
			prefix = "";
		} else {
			prefix = s[0];
			for(int i = 0; i < len; i ++) {
				while(s[i].indexOf(prefix) != 0) {
					prefix = prefix.substring(0, prefix.length() -1);
					
					if(prefix.length() < 1) prefix = "";
				}
			}
		}
		
		return prefix;
	}

}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.

JAVA-알고리즘 Leetcode(Easy)-Roman to Integer

JAVA-알고리즘 Leetcode(Easy)-Valid Parentheses