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:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Compare characters column by column across all strings.
Algorithm:
1class Solution {
2 public String longestCommonPrefix(String[] strs) {
3 if (strs == null || strs.length == 0) {
4 return "";
5 }
6
7 for (int i = 0; i < strs[0].length(); i++) {
8 char c = strs[0].charAt(i);
9
10 for (int j = 1; j < strs.length; j++) {
11 if (i >= strs[j].length() || strs[j].charAt(i) != c) {
12 return strs[0].substring(0, i);
13 }
14 }
15 }
16
17 return strs[0];
18 }
19}