Here you can find the source of longestCommonPrefix(String[] strs)
public static String longestCommonPrefix(String[] strs)
//package com.java2s; //License from project: Apache License public class Main { public static String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) { return ""; }//from w w w . j a v a 2s . c om if (strs.length == 1) { return strs[0]; } StringBuilder prefix = new StringBuilder(); int idx = 0; while (true) { if (idx >= strs[0].length()) { return prefix.toString(); } char c = strs[0].charAt(idx); boolean match = true; for (int i = 1; i < strs.length; i++) { if (strs[i] == null || idx >= strs[i].length()) { return prefix.toString(); } if (strs[i].charAt(idx) != c) { match = false; break; } } if (match) { prefix.append(c); idx++; } else { return prefix.toString(); } } } }