MCPcopy Create free account
hub / github.com/ROUTINE-STUDY/Algorithm / Sanghoo

Class Sanghoo

LeetCode/String/14. Longest Common Prefix/Sanghoo.java:9–47  ·  view source on GitHub ↗

https://leetcode.com/problems/longest-common-prefix/

Source from the content-addressed store, hash-verified

7 * https://leetcode.com/problems/longest-common-prefix/
8 */
9public class Sanghoo {
10
11 public String longestCommonPrefix(String[] strs) {
12 String res = "";
13
14 // 문자열 길이가 작은 순으로 내림차순 정렬
15 Arrays.sort(strs, new Comparator<String>() {
16 @Override
17 public int compare(String o1, String o2) {
18 if(o1.length() > o2.length()) return 1;
19 if(o1.length() < o2.length()) return -1;
20 return 0;
21 }
22 });
23
24 StringBuilder standard = new StringBuilder(strs[0]); // 기준이되는 첫 번째 문자열
25 for(int i=standard.length()-1; i>=0; i--) {
26 boolean isEquals = true; // 일치하는지 확인하기 위한 flag 값
27
28 for(int j=1; j<strs.length; j++) {
29 String str = strs[j].substring(0, standard.length()); // 기준과 똑같은 인덱스로 잘라낸 문자열
30
31 if(!str.equals(standard.toString())) { // 같은지 판단 후 하나라도 다르다면 flag false 후 break
32 isEquals = false;
33 break;
34 }
35 }
36
37 if(isEquals) { // 모두 같다면 return value 저장 후 break
38 res = standard.toString();
39 break;
40 }
41 standard = standard.deleteCharAt(i); // 기준 문자열 꼬리부터 하나씩 제거
42 }
43
44 return res;
45 }
46
47}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected