集册 Java实例教程 一个确定两个字符串是否为anagrams的方法,如果字符串相同,则返回true

一个确定两个字符串是否为anagrams的方法,如果字符串相同,则返回true

欢马劈雪     最近更新时间:2020-01-02 10:19:05

398
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
一个确定两个字符串是否为anagrams的方法,如果字符串相同,则返回true


//package com.nowjava;


public class Main {
/**来自 
 N o w J a v a . c o m**/

    public static void main(String[] argv) throws Exception {

        String s1 = "nowjava.com";

        String s2 = "nowjava.com";

        System.out.println(areAnagrams(s1, s2));

    }


    /**

     * A method to determine if two string are anagrams, will return true if the

     * strings are the same

     * 

     * @param s1

     * @param s2

     * @return true if the two input words are anagrams and false if otherwise

     */

    public static boolean areAnagrams(String s1, String s2) {

        // Compare the sorted strings

        return sort(s1).equals(sort(s2));/* 来 自 nowjava - 时代Java*/

    }


    /**

     * Sorts each character of a string parameter using insertion sort

     * 

     * @param myString

     * @return the sorted version of the input string as a string

     */

    public static String sort(String myString) {


        if (myString.length() == 0) {

            return "";

        } else {

            // Sort should not be case sensitive

            myString = myString.toLowerCase();

            // Calls the helper method to get an array of chars

            char[] myWord = toArray(myString);


            // Do the insertion sort

            for (int i = 1; i < myWord.length; i++) {

                int j;

                for (j = i - 1; j >= 0 && (myWord[j] >= myString.charAt(i)); j--) {

                    myWord[j + 1] = myWord[j];

                }

                myWord[j + 1] = myString.charAt(i);

            }

            String finalWord = "";

            // Read the sorted characters of myWord into finalWord

            for (int i = 0; i < myWord.length; i++) {

                finalWord += myWord[i];

            }

            return finalWord;

        }

    }


    /**

     * A helper method used when sorting a word

     * 

     * @param myString

     * @return an array of chars containing all of the characters of the input

     *         string

     */

    
展开阅读全文