## 문제
(Logest Common Prefix)[https://leetcode.com/problems/longest-common-prefix/submissions/]
## 작성코드
```java
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) { return "";}
System.out.print(strs[0]);
String commonPrefix = "";
for (int i = 0; i < strs[0].length(); i++) {
for (int k = 0; k < strs.length - 1; k++) {
if (strs[k].length() <= i || strs[k+1].length() <= i) {
return commonPrefix;
} else if (strs[k].charAt(i) != strs[k+1].charAt(i) ) {
return commonPrefix;
}
}
commonPrefix += strs[strs.length - 1].charAt(i);
}
return commonPrefix;
}
}
```
## 배운점
- indexOf() 를 사용하면 일치하는 문자열의 첫 시작을 알 수 있다.
- 첫 문자열을 기본으로 틀릴때마다 뒤에 길이를 1씩 줄임으로써 비교하는 것이 좋다.
'코테 > LeetCode' 카테고리의 다른 글
<LeetCode>04_13_Roman To Integer (0) | 2021.02.09 |
---|---|
<LeetCode>03_09_Palindrome Number (0) | 2021.02.09 |
<LeetCode>02_07_ReverseInteger (0) | 2021.02.09 |
<LeetCode>01_01_TwoSum (0) | 2021.02.09 |