算法练习篇之:字符串的排列 (字符串)

算法练习篇之:字符串的排列 (字符串)

题目描述

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

输入描述:

解题思路

我们求整个字符串的排列,其实可以看成两步:

第一步求所有可能出现在第一个位置的字符(即把第一个字符和后面的所有字符交换[相同字符不交换]);
第二步固定第一个字符,求后面所有字符的排列。这时候又可以后面的所有字符拆成两部分(第一个字符以及剩下的所有字符),依此类推。这样,我们就可以用递归的方法来解决。

代码实现

博客设置页面,选择一款你喜欢的代码片高亮样式,下面展示同样高亮的 代码片.

import java.util.ArrayList;
import java.util.Collections;

public class strPermutation {
    //字符串的排列组合

    ArrayList<String> res=new ArrayList<>();
    public ArrayList<String> permutation(String str){
        if (str==null){
            return res;
        }
        permutationHelper(str.toCharArray(),0);
        Collections.sort(res);
        return res;

    }

    public void permutationHelper(char[] str,int i){
        if (i==str.length-1){
            res.add(String.valueOf(str));
        }else {
            for (int j=i;j<str.length;j++){
                if (j!=i&&str[i]==str[j]){
                    continue;
                }
                swap(str,i,j);
                permutationHelper(str,i+1);
                swap(str,i,j);
            }
        }
    }
    public void swap(char[] str,int i,int j){
        char temp=str[i];
        str[i]=str[j];
        str[j]=temp;
    }
    public static void main(String[] args) {
        strPermutation test=new strPermutation();
        ArrayList<String> res=test.permutation("abc");
        System.out.println(res);
    }
}


class Solution {
    List<String> list=new ArrayList<>();
    public String[] permutation(String s) {
        if (s==null||s.length()==0){
            return null;
        }
        char[] ch=s.toCharArray();
        dfs(ch,0);
        return list.toArray(new String[list.size()]);
    }
    public void dfs(char[] ch,int x){
        if (x== ch.length-1){
            list.add(String.valueOf(ch));
            return;
        }
        HashSet<Character> set=new HashSet<>();
        for (int i=x;i<ch.length;i++){
            if (set.contains(ch[i])){
                continue;
            }
            set.add(ch[i]);
            swap(ch,i,x);
            dfs(ch,x+1);
            swap(ch,i,x);
        }

    }
    public void swap(char[] ch,int i,int j){
        char tmp=ch[i];
        ch[i]=ch[j];
        ch[j]=tmp;
    }

}

总结

本题来源于面试经典教材《剑指offer》中 归属于全排序类型题目。
同许多在算法道路上不断前行的人一样,不断练习,修炼自己!
如有博客中存在的疑问或者建议,可以在下方留言一起交流,感谢各位!
最后,感谢AIAS!

觉得本博客有用的客官,可以给个赞鼓励下! 嘿嘿

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值