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.length == 0) return ""; int i = 0; String prefix = ""; String result = ""; boolean broken = false; while (true) { i++;/*w w w.j a v a 2s. co m*/ result = prefix; if (i > strs[0].length()) break;//this will break out the while loop prefix = strs[0].substring(0, i); for (String word : strs) { if (i > word.length() || !word.startsWith(prefix)) { broken = true; break;//this will only break out of the for loop } } if (broken) break;//this will break out the while loop } return result; } }