zoukankan      html  css  js  c++  java
  • ***剑指offer——字符串的排列(不会)

    字符串的排列

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

    解:就是将字符串abc当前位置的字符和下一个字符进行交换,递归

    import java.util.ArrayList;
    import java.util.TreeSet;
    public class Solution {
        public ArrayList<String> Permutation(String str) {
           ArrayList<String> arrayList = new ArrayList<>();
            if(str == null || str.length() == 0) return arrayList;
            char[] ch = str.toCharArray();
            TreeSet<String> res = new TreeSet<>();
            getsubStr(res, ch, 0);
            arrayList.addAll(res);
            return arrayList;
        }
        public void getsubStr(TreeSet<String> res, char[] ch, int index){
            if(index == ch.length - 1){
                 res.add(String.valueOf(ch));
            } else{
                for(int i = index; i < ch.length; i++){
                    swap(ch, index, i);
                    getsubStr(res, ch, index + 1);
                    swap(ch, index, i);
                }
            }
        }
        public void swap(char[] ch, int i, int j){
            char temp = ch[i];
            ch[i] = ch[j];
            ch[j] = temp;
        }
    }
    

      

  • 相关阅读:
    MySQL开发规范与使用技巧总结
    Anaconda3(在D盘)安装jieba库具体步骤
    Python的reshape的用法
    oom和cpu负载的定位
    接口安全设计
    恍然间
    java原子类
    设计模式
    微服务
    常见的代码优化
  • 原文地址:https://www.cnblogs.com/SkyeAngel/p/8674999.html
Copyright © 2011-2022 走看看