题解 | #最长公共前缀#

最长公共前缀

http://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47

使用java的contians方法

import java.util.*;


public class Solution {
    /**
     * 
     * @param strs string字符串一维数组 
     * @return string字符串
     */
    public String longestCommonPrefix (String[] strs) {
        // write code here
        if (strs.length == 0) {
            return "";
        }

        String pre = strs[0];

        for (int i = 1; i < strs.length; i++) {
            while(!strs[i].contains(pre)) {
                pre = pre.substring(0,pre.length() - 1);
            }
        }

        return pre;
    }
}

将String数组第一个元素最为最长前缀向后判断,如果后面的字符串不包含此前缀,前缀的长度减一。

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务