I try to solve the problem 14 on leetcode, which is to write a function to find the longest common prefix string amongst an array of strings. Here is my code, the result I expect is "f" while the result I got is "". Can someone help me out here? Thanks!
class Solution {
String[] strsa={"fsd","fds","fgsdgf","fggdgdgd"};
String prefix=longestCommonPrefix(strsa);
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
String result = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(result) != 0) {
result = result.substring(0, result.length() - 1);
}
}
return result;
}
}
Here is the result enter image description here