반응형
Leetcode - 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 "".
Example:
Input: strs = ["flower","flow","flight"]
Output: "fl"
제한사항
- 0 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] consists of only lower-case English letters.
소스코드
class Solution {
public String longestCommonPrefix(String[] strs) {
String str = "";
boolean isDone = false;
if (strs.length > 0) {
for (int i=0; i<strs[0].length(); i++) {
char c = strs[0].charAt(i);
str += String.valueOf(c);
for (int j=1; j<strs.length; j++) {
if (!strs[j].startsWith(str)) {
isDone = true;
break;
}
}
if (isDone) {
str = str.substring(0, str.length() - 1);
break;
}
}
}
return str;
}
}
반응형