排序ArrayList的字母 [英] Sort ArrayList alphabetically

查看:92
本文介绍了排序ArrayList的字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一个字符串的所有排列,并将它们按字母顺序排序。

I'm trying to find all permutations of a string and sort them alphabetically.

这是我迄今为止:

public class permutations {

        public static void main(String args[]) {
            Scanner s = new Scanner(System.in);
            System.out.print("Enter String: ");
            String chars = s.next();
            findPerms("", chars);
        }

        public static void findPerms(String mystr, String chars) {

            List<String> permsList = new ArrayList<String>();

                if (chars.length() <= 1)
                        permsList.add(mystr + chars);
                        //System.out.print(mystr + chars + " ");

                else
                        for (int i = 0; i < chars.length(); i++) {
                            String newString = chars.substring(0, i) + chars.substring(i + 1);
                            findPerms(mystr + chars.charAt(i), newString);
                        }

               Collections.sort(permsList);

               for(int i=0; i<permsList.size(); i++) {
                    System.out.print(permsList.get(i) + " ");
               }
       }
}

如果我输入一个字符串玩具我得到:

IF I enter a string "toys" I get:

玩具tosy tyos tyso tsoy tsyo otys otsy oyts oyst osty osyt ytos YouTube交响乐团yots约斯特ysto ysot斯托伊styo soty soyt SYTO syot

toys tosy tyos tyso tsoy tsyo otys otsy oyts oyst osty osyt ytos ytso yots yost ysto ysot stoy styo soty soyt syto syot

我是什么做错了。我怎样才能让他们按字母顺序排列?谢谢!

What am I doing wrong. How can I get them in alphabetical order? Thanks!

推荐答案

您是从发现你的字符串的所有排列的递归方法中调用你的排序过程,它已经完全填充之前

You're calling your sort routine from within the recursive method that finds all permutations of your String, before it's been fully populated

import java.util.*;

public class permutations {

        public static void main(String args[]) {
            Scanner s = new Scanner(System.in);
            System.out.print("Enter String: ");
            String chars = s.next();
            List<String> myList = new ArrayList<String>();
            findPerms(myList, "", chars);

            Collections.sort(myList);

            for(int i=0; i<myList.size(); i++) {
               System.out.print(myList.get(i) + " ");
            }

        }

        public static void findPerms(List<String> permsList, String mystr, String chars) {

            if (chars.length() <= 1)
                permsList.add(mystr + chars);    
            else
            for (int i = 0; i < chars.length(); i++) {
                String newString = chars.substring(0, i) + chars.substring(i + 1);
                findPerms(permsList, mystr + chars.charAt(i), newString);
            }

       }
}

这篇关于排序ArrayList的字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆