字符串数组排序,如果可以保证前一个字符的末尾与后一个字符的开头相同,返回1,否则返回-1

  今天在中兴的笔试模拟题里看到了这样的一个算法题:

  一个字符串数组String[] arr,将其按照如下的方式排列:前一个字符串的末尾字符与后一个字符串的起始字符相同,比如["ab", "bc", "cd"],则返回1;如果无法形成这样的排列,则返回-1.

 

  本菜鸡一开始我也没想出思路,递归,动规,想了一圈也没写出来。只能使出百度大发,在https://segmentfault.com/q/1010000005152540看到了思路:使用dfs算法。

  1.首先根据字符串数组简历邻接表存储,每个链表存储起始字符与当前字符的末尾字符相同的字符串数组元素的下标。

  2.字符串数组的元素依次作为dfs算法的起始点,每次执行dfs算法,访问到一个未被访问过的节点,则计数加1,如果计数值等于字符串数组的长度,则表示找到了这么衣蛾排列方式,返回1。

   如果所有的字符串数组的元素都遍历过,任然没有找到这么一种排列,则返回-1.

  代码如下,如有错误请指出:

import java.util.LinkedList;
import java.util.List;

public class Solution {

    /**
     * @param args
     */
    static boolean[] visited = null;
    static int count = 0;
    static int totalNum = 0;
    static boolean flag = false;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] arr = { "ab", "de", "bf", "cd" };
        System.out.println(isLinked(arr));
    }

    public static int isLinked(String[] arr) {

        if (arr == null || arr.length == 0) {
            return -1;
        }
        totalNum = arr.length;
        List<LinkedList<Integer>> list = new LinkedList<LinkedList<Integer>>();
        for (int i = 0; i < arr.length; i++) {
            List<Integer> tmpList = new LinkedList<Integer>();
            for (int j = 0; j < arr.length; j++) {
                if (i != j
                        && arr[i].charAt(arr[i].length() - 1) == arr[j]
                                .charAt(0)) {
                    tmpList.add(j);
                }
            }
            list.add((LinkedList<Integer>) tmpList);
        }

        
        for(int i = 0; i < arr.length; i++){
            count = 0;
            visited = new boolean[arr.length];
            dfs(list, i);
            if(flag){
                return 1;
            }
        }
        return -1;

    }

    private static void dfs(List<LinkedList<Integer>> list, int index) {

        count++;
        visited[index] = true;
        if(count == totalNum){
            flag = true;
        }
        boolean flag = false;
        for(int i : list.get(index)){
            if(!visited[i]){
                dfs(list, i);
            }
        }

    }

 

posted @ 2017-08-23 14:51  银河末班车  阅读(139)  评论(0编辑  收藏  举报