finding if two words are anagrams of each other

后端 未结 22 1232
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 14:51

I am looking for a method to find if two strings are anagrams of one another.

Ex: string1 - abcde
string2 - abced
Ans = true
Ex: string1 - abcde
string2 - ab         


        
22条回答
  •  粉色の甜心
    2020-11-27 15:06

    The steps are:

    1. check the length of of both the words/strings if they are equal then only proceed to check for anagram else do nothing
    2. sort both the words/strings and then compare

    JAVA CODE TO THE SAME:

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package anagram;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Arrays;
    
    /**
     *
     * @author Sunshine
     */
    public class Anagram {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) throws IOException {
            // TODO code application logic here
            System.out.println("Enter the first string");
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String s1 = br.readLine().toLowerCase();
            System.out.println("Enter the Second string");
            BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
            String s2 = br2.readLine().toLowerCase();
            char c1[] = null;
            char c2[] = null;
            if (s1.length() == s2.length()) {
    
    
                c1 = s1.toCharArray();
                c2 = s2.toCharArray();
    
                Arrays.sort(c1);
                Arrays.sort(c2);
    
                if (Arrays.equals(c1, c2)) {
                    System.out.println("Both strings are equal and hence they have anagram");
                } else {
                    System.out.println("Sorry No anagram in the strings entred");
                }
    
            } else {
                System.out.println("Sorry the string do not have anagram");
            }
        }
    }
    

提交回复
热议问题