Longest Common Substring

    public int longestCommonSubstring(String A, String B) {
        // write your code here
        int len = 0;
        String tp = "";
        if (A.length() < B.length()) {
            tp = B;
            B = A;
            A = tp;
        }
        for (int i = 0; i < A.length(); ++i) {
            int mLen= 0;
            for (int j = 0; j < B.length() && i + j < A.length(); ++j) {
                if (A.charAt(i + j) == B.charAt(j)) {
                    mLen++;
                    if (mLen > len) len = mLen;
                } else {
                    mLen = 0;
                }
            }
        }
        return len;
    }
View Code

 更简洁的解法:

    int longestCommonSubstring(string &A, string &B) {
        // write your code here
        int lenA = A.length();
        int lenB = B.length();
        int mLen = 0;
        for (int i = 0; i < lenA; ++i) {
            for (int j = 0; j < lenB; ++j) {
                int len = 0;
                while (i + len < lenA && j + len < lenB && A[i + len] == B[j + len]) {
                    ++len;
                    if (len > mLen) {
                        mLen = len;
                    }
                }
            }
        }
        return mLen;
    }
View Code 

Longest Common Prefix

    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) return "";
        String pre = strs[0];
        for (int i = 1; i < strs.length; ++i) {
            String tmp = "";
            for (int j = 0; j < strs[i].length() && j < pre.length(); ++j) {
                if (strs[i].charAt(j) == pre.charAt(j)) {
                    tmp += strs[i].charAt(j);
                } else {
                    break;
                }
            }
            pre = tmp;
        }
        return pre;
    }
View Code 

String to Integer(atoi)

    public int atoi(String str) {
        // write your code here
        int INT_MAX = 2147483647;
        int INT_MIN = -2147483648;
        int ret = 0;
        int sign = 1;
        if (str == null || str.length() == 0) return 0;
        int i = 0;
        while (str.charAt(i) == ' ') {
            ++i;
        }
        if (str.charAt(i) == '-') {
            sign = -1;
            ++i;
        } else if (str.charAt(i) == '+') {
            sign = 1;
            ++i;
        }
        for (; i < str.length(); ++i) {
            if (str.charAt(i) == ' ') continue;
                if (str.charAt(i) < '0' || str.charAt(i) > '9') return ret * sign;
                ret = ret * 10 + (str.charAt(i) - '0');
        }
        ret *= sign;
        if (sign > 0 && ret < 0) return INT_MAX;
        if (sign < 0 && ret > 0) return INT_MIN;
        return ret;
    }
View Code