每天刷一道牛客题霸-第26天- 最长公共前缀

题目

https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47?tpId=190&&tqId=35964&rp=1&ru=/activity/oj&qru=/ta/job-code-high-rd/question-ranking

import java.util.*;


public class Solution {
    /**
     * 
     * @param strs string字符串一维数组 
     * @return string字符串
     */
    public String longestCommonPrefix (String[] str) {
        StringBuilder result = new StringBuilder();
        int index = 0;
        if(str.length == 0){
            return result.toString();
        }
        boolean count = true;
        char item;
        while (count){
            if (str[0].length() == 0){
                return result.toString();
            }
            if (index >= str[0].length()){
                break;
            }else {
                item = str[0].charAt(index);
            }
            for (int i = 1 ; i < str.length ; i++){
                if (index >= str[i].length()){
                    count = false;;
                    break;
                }
                if (item != str[i].charAt(index)){
                    count = false;
                    break;
                }
            }
            if (count){
                result.append(item);
            }
            index++;
        }
        return result.toString();
        // write code here
    }
}
#牛客题霸##题解#
全部评论

相关推荐

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