Friday, November 27, 2015

[leetcode]Longest common prefix

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Solution {
    public String longestCommonPrefix(String[] strs) {
        String result = "";
        int travel = findShortest(strs);
        char current;
        boolean findDiff = false;
        for (int i = 0; i < travel && !findDiff; i++){
            findDiff = false;
            current = strs[0].charAt(i);
            for (int j = 1; j < strs.length && !findDiff; j++){
                if (current != strs[j].charAt(i)) findDiff = true;
            }
            if (!findDiff) result+=current;
        }
           
        return result;
    }
    
    int findShortest(String[] strs){
        if (strs == null || strs.length == 0) return 0;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < strs.length; i++){
            min = Math.min(min, strs[i].length());
        }
        return min;
    }
}

No comments:

Post a Comment