挚文第一题开始一脸懵,等会了时间不够了,好气

public class Solution {

    public String maxPath(String[] paths){
        int n = paths.length;
        int[] nextString = new int[n];
        for (int i = 0; i < n; i++) {
            nextString[i] = -1;
            int a = paths[i].length();
            for (int j = 0; j < n; j++) {
                if (i == j) continue;
                if (paths[i].charAt(a - 1) == paths[j].charAt(0)) nextString[i] = j;
            }
        }

        int[] ll = new int[n];
        for (int i = 0; i < n; i++) {
            ll[i] = paths[i].length();
            int k = i;
            while (k < n) {
                if (nextString[k] == -1) break;
                ll[i] += paths[nextString[k]].length();
                k = nextString[k];
            }
        }

        int maxLen = -1;
        int pos = -1;
        for (int i = 0; i < n; i++) {
            if (ll[i] > maxLen) {
                maxLen = ll[i];
                pos = i;
            }
        }

        if (pos == -1 || maxLen == -1) return "";

        int k = pos;
        String s = paths[pos];
        while (k < n) {
            if (nextString[k] == -1) break;
            s += paths[nextString[k]].substring(1);
            k = nextString[k];
        }

        return s;
    }

    public static void main(String[] args) {
        String[] paths = {"B->C", "C->D->E", "L->M->N"};
        Solution solution = new Solution();
        String s = solution.maxPath(paths);
        System.out.println(s);
    }

}

#挚友集团#
全部评论

相关推荐

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