• 剑指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; } }

      

  • 相关阅读:
    Redis 的 5 个常见使用场景
    当别人给你一个wsdl或者webservice接口时
    Java事务
    Java分布式锁的三种实现方案(redis)
    使用Redis数据库(String类型)
    超详细Redis数据库入门教程
    java对redis的基本操作(初识)
    String、StringBuffer与StringBuilder之间区别
    java正则表达式替换空格和换行符
    Linux 批量管理工具
  • 原文地址:https://www.cnblogs.com/MrSaver/p/9244299.html
Copyright © 2020-2023  润新知