美文网首页
面试题38:字符串的排列

面试题38:字符串的排列

作者: scott_alpha | 来源:发表于2019-10-08 13:53 被阅读0次

    题目:输入一个字符串,打印出该字符串中字符的所有排列。
    思路:使用递归来做,
    解决方案:
    ···
    public class Question38 {
    public static void permutation(char[] str){
    if (str == null) return;
    permutation(str, 0);

    }
    private static void permutation(char[] str,int begin){
        if (begin == str.length - 1) {
            String result = new String(str);
            System.out.println(result);
        }else {
            for (int i=0; i<str.length; i++){
                swap(str, begin, i);
                permutation(str, begin+1);
                swap(str, begin, i);
            }
        }
    }
    private static void swap(char[] str, int index1, int index2){
        char tmp = str[index1];
        str[index1] = str[index2];
        str[index2] = tmp;
    }
    
    public static void main(String[] args) {
        String str = "abc";
        char[] arr = str.toCharArray();
        permutation(arr);
    }
    

    }
    ···

    相关文章

      网友评论

          本文标题:面试题38:字符串的排列

          本文链接:https://www.haomeiwen.com/subject/eprbpctx.html