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

      

  • 相关阅读:
    json2.js和wcf传递Date对象问题
    使用WebClient发送POST请求
    我也质疑下petshop
    sql server 2005 游标使用小例
    关于SCOPE_IDENTITY、IDENT_CURRENT 和 @@IDENTITY
    小错误大麻烦
    SQL Server启动出现“指定的服务未安装”的解决方法
    非常不错的一个网站
    objectdatasource 未能找到带参数的非泛型方法
    SQLServer日志文件收缩
  • 原文地址:https://www.cnblogs.com/MrSaver/p/9244299.html
Copyright © 2011-2022 走看看