1 public class Solution { 2 public string LongestCommonPrefix(string[] strs) { 3 int len = strs.Length; 4 5 if(len == 0) 6 return ""; 7 8 string result = ""; 9 int minSize = 100000; 10 int minIndex = 0; 11 12 if(len == 1){ 13 result = strs[0]; 14 return result; 15 } 16 17 for(int i = 0; i < len; i++){ 18 int size = strs[i].Length; 19 if(size < minSize){ 20 minSize = size; 21 minIndex = i; 22 } 23 } 24 25 for(int i = minSize; i >= 0; i--){ 26 result = strs[minIndex].Substring(0,i); 27 28 int j = 0; 29 for(; j < len; j++){ 30 if(j == minIndex) 31 continue; 32 string temp = strs[j].Substring(0,i); 33 if(result != temp) 34 break; 35 } 36 if(j == len) 37 return result; 38 } 39 return result; 40 } 41 }
內層循環的這個continue,會跳事後面的語句可是j++會執行spa
而break不執行j++ ,也就是當前的result若是不是最長前綴,j的值就不會是len,.net
https://blog.csdn.net/NoMasp/article/details/49184355code
放一下這個大神的連接~他的解法提醒了我break和continue的用法。blog
書上說:string
break是跳過循環,而continue是跳過本次迭代。io