剑指offer面试题38:字符串的排列(没做出来,要好好看)

这道题对于字符串的处理,要好好看

直接贴上了别人的代码(https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/solution/mian-shi-ti-38-zi-fu-chuan-de-pai-lie-hui-su-fa-by/

可以参考的地方很多

因为直接对String类型的每个字符操作不可取,因此使用了

c = s.toCharArray();

变成char数组来操作

因此也使用

List<String> res = new LinkedList<>();

return res.toArray(new String[res.size()]);

来得到String[]的结果

并且使用Hashmap来剔除字符串中重复的字符带来的不必要的运算和重复结果

这道题的思路是,将字符串中的字符依次交换,

class Solution {
    List<String> res = new LinkedList<>();
    char[] c;
    public String[] permutation(String s) {
        if(s == null){
            return null;
        }
        c = s.toCharArray();
        dfs(0);
        return res.toArray(new String[res.size()]);
    }

    void dfs(int index){
        if(index == c.length - 1){
            res.add(String.valueOf(c));
            return ;
        }
        HashSet<Character> set = new HashSet<>();
        for(int count = index;count < c.length;count++){
            if(set.contains(c[count])) continue; // 重复,因此剪枝
            set.add(c[count]);
            swap(count,index);
            dfs(index+1);
            swap(count,index);
        }
    }

    void swap(int count,int index){
        char temp = c[index];
        c[index] = c[count];
        c[count] = temp;
    }


}

猜你喜欢

转载自blog.csdn.net/qq_40473204/article/details/114390893