Checking if two strings are permutations of each other

前端 未结 30 1009
感情败类
感情败类 2020-12-05 08:19

How to determine if two strings are permutations of each other

30条回答
  •  北海茫月
    2020-12-05 09:00

    Linear Time solution in HashMap. Traverse and put first String in HashMap, keep the count of each character. Traverse second String and if it is already in the hashmap decrease the count by 1. At the end if all character were in the string the value in hashmap will be 0 for each character.

    public class StringPermutationofEachOther {
        public static void main(String[] args)
        {
    
        String s1= "abc";
        String s2 ="bbb";
        System.out.println(perm(s1,s2));
    }
        public static boolean perm(String s1, String s2)
        { HashMap map = new HashMap();
        int count =1;
            if(s1.length()!=s2.length())
            {
                return false;
            }
                for(Character c: s1.toCharArray())
                {
                    if(!map.containsKey(c))
                        map.put(c, count);
    
                    else
                        map.put(c, count+1);
    
                }
                for(Character c: s2.toCharArray())
                {
                    if(!map.containsKey(c))
                        return false;
    
                    else
                        map.put(c, count-1);
                }
                for(Character c: map.keySet())
                {
                    if(map.get(c)!=0)
                        return false;
                }
            return true;
        }
    
    
    }
    

提交回复
热议问题