zoukankan      html  css  js  c++  java
  • 剑指Offer:字符串排列【38】

    剑指Offer:字符串排列【38】

    题目描述

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

    题目分析

      

    Java题解

    package str;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    
    public class StrPermutation {
    
        public static ArrayList<String> Permutation(String str) {
            if(str==null)
                return new ArrayList<>();
            ArrayList<String> list = new ArrayList<>();
            PermutationCore(str.toCharArray(),0,list);
    ArrayList<String> newList = new ArrayList<>();//去除重复元素,比如aa这种,按我们的方式有aa,aa,但是实质结果只有一个aa Iterator<String> it = list.iterator(); while (it.hasNext()) { String temp = it.next(); if(!newList.contains(temp)) newList.add(temp); } Collections.sort(newList);//字典序排序 return newList; } public static void main(String[] args) { ArrayList<String> list= Permutation("abc"); Iterator<String> it = list.iterator(); while (it.hasNext()) System.out.println(it.next()); } public static void PermutationCore(char[] str,int ptr,ArrayList<String> res) { //递归的结束条件 if(ptr==str.length) { res.add(new String(str)); return; } //循环部分 for(int i = ptr;i<str.length;i++) { Swap(str,ptr,i); PermutationCore(str,ptr+1,res); Swap(str,ptr,i); } }   //交换 public static void Swap(char[] str,int i,int j) { char temp = str[i]; str[i] = str[j]; str[j] = temp; } }

      

  • 相关阅读:
    hive之窗口函数
    linux环境下Mysql的卸载和重新安装和启动
    2017ACM暑期多校联合训练
    2017ACM暑期多校联合训练
    状态压缩dp
    铺砖问题 (状态压缩dp)
    POj 2104 K-th Number (分桶法+线段树)
    POJ 2991 Crane (线段树)
    4 Values whose Sum is 0 POJ 2785 (折半枚举)
    Billboard HDU 2795 (线段树)
  • 原文地址:https://www.cnblogs.com/MrSaver/p/9244299.html
Copyright © 2011-2022 走看看