- Longest Common Prefix
Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
Solution:
1. public class 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. for (int j = 1; j < strs.length; j++) {
9. if (i >= strs[j].length() || strs[j].charAt(i) != strs[0].charAt(i)) {
10. return strs[0].substring(0, i);
11. }
12. }
13. }
14. 15. return strs[0];
16. }
17. }
