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; } }

      

  • 相关阅读:
    在ASP.NET应用程序中使用身份模拟(Impersonation)
    在VS项目中使用SVN版本号作为编译版本号
    android学习网站
    RFID:ISO14443、15693、18000体系分析
    android-custom-tab-with-viewpager
    DoubleViewPager
    RecyclerViewDemo
    FragmentSharedFabTransition
    Material-Animations
    MaterialImageLoading
  • 原文地址:https://www.cnblogs.com/MrSaver/p/9244299.html
Copyright © 2011-2022 走看看