首页 > 其他分享 >【LeeCode】字符串的全排列

【LeeCode】字符串的全排列

时间:2022-10-29 23:31:57浏览次数:111  
标签:字符 排列 String list length LeeCode str 字符串 new

【题目描述】

输入字符串str, 返回str的字符的全排序


【示例】

输入:qwe

输出:qwe qew ewq eqw wqe weq

注意: 如果输入的是n个相同的字符,那么也就只有1种排列组合


【代码】

list: 保留最后的结果,且初始字符为str的第一个字母

new_list: 保留中间结果, 且每次把新的字符加到原字符的左右, 然后利用

                 substring进行字符拼接

package com.company;

import java.util.*;

/**
* 2022-06-18
*/
public class Test {
public static void main(String[] arg) {
String str = "aaaa";
quanpai(str);
}

private static void quanpai(String str) {
if (str.length() == 0) {
return;
}else if(str.length() == 1){
System.out.println("共计: " + 1);
return;
}
// 如果输入的都是n个相同字符串,那么也就1种排列组合,这里不考虑这个场景

List<String> list = new ArrayList<>();
// 添加首字母
list.add(str.charAt(0) + "");
// 外层循环负责获取每次的字符
for (int i = 1; i < str.length(); i++) {
List<String> new_list = new ArrayList<>();
// 获取第二个字符
char ch = str.charAt(i);
for (String s : list) {
// 第二个字符只有2个选择,放在第一个的前面或者后面
new_list.add(s + ch);
new_list.add(ch + s);
// 注意这里从1开始,因为0就是起始值且subString(0,j)
for (int j = 1; j < s.length(); j++) {
String tmp = s.substring(0, j) + ch + s.substring(j);
new_list.add(tmp);
}
}
list = new_list;
}
System.out.println("共计: " + list.size());

for (String ss : list) {
System.out.print(ss + " ");
}
}
}


典型Leecode: ​​https://leetcode.cn/problems/permutation-in-string/​



标签:字符,排列,String,list,length,LeeCode,str,字符串,new
From: https://blog.51cto.com/u_13682316/5806601

相关文章

  • js字符串转字节
    functionstringToByte(str){varlen,c;len=str.length;varbytes=[];for(vari=0;i<len;i++){c=str.charCodeAt(i);if(c>=0x010000&......
  • golang中的字符串
    0.1、索引​​https://waterflow.link/articles/1666449874974​​1、字符串编码在go中rune是一个unicode编码点。我们都知道UTF-8将字符编码为1-4个字节,比如我们常用的汉字......
  • 【LeeCode】字符串的排列
    【题目描述】给你两个字符串 ​​s1​​​ 和 ​​s2​​​ ,写一个函数来判断 ​​s2​​​ 是否包含 ​​s1​​ 的排列。如果是,返回 ​​true​​​ ;否则,返回 ......
  • 【LeeCode】汇总
    ​​【LeeCode】排序算法​​​​【LeeCode】颜色分类​​​​【LeeCode】三数之和​​......
  • 字符串分割(2)
    #include<iostream>#include<string>usingnamespacestd;intmain(){ stringstr="雷猴,我是李玉波,我今年上八年级;"; //replace是替换的意思 //一个汉字是两......
  • 字符串分割(3)
    #include<iostream>#include<string>usingnamespacestd;intmain(){ stringa;stringstr="a:=3;b:=4;c:=5;";intindex=str.find(";");a=str.su......
  • 字符串
    #include<iostream>#include<string>usingnamespacestd;intmain(intargc,char**argv){ stringstr="a:=3;b:=4;c:=5;"; stringa; intm=str.find(";"......
  • python字符串
    1、利用切片反转判断回文数 (1)大小写字母换来换去的方法(因为字符串是不可变的,所以它只是生成了一个新的对象。)capitalize():将字符串的首字母变为大写,其他字母变成小写。......
  • 字符串
    day06字符串字符串的概述字符串基础数据类型属于值类型,值类型是不可以改变的。字符串的相关方法是不能改变原本的字符串的,以返回一个新的字符串做为对应的特性。字符串......
  • 去掉字符串中最后一个字母
    问题:无规律的字符串中,最后一个是字母的去掉,是数字的保留。函数解决: =IF(ISERROR(-RIGHT(A1)),LEFT(A1,LEN(A1)-1),A1)解题思路:LEFT(A1,LEN(A1)-1)是去掉最后一位......