題目:

Write a function to find the longest common prefix string amongst an array of strings.

 

思路:

比較所有String中最小相同開頭的字串.

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public static String longestCommonPrefix(String[] strs) {
	if(strs.length == 0)
		return "";
	
	String res = strs[0];
	
	for(int i=1;i<strs.length;i++){
		String tempStr = strs[i];
		int min_size = tempStr.length() > res.length() ? res.length() : tempStr.length();
		res= res.substring(0,min_size);
		for(int j=0;j<min_size;j++){
			if(tempStr.charAt(j)!= res.charAt(j)){
				
				res = res.substring(0, j);
				break;
			}
		}
	}
	return res;
}
arrow
arrow
    文章標籤
    leetcode Easy
    全站熱搜

    Lung-Yu,Tsai 發表在 痞客邦 留言(0) 人氣()