Checking if two strings are permutations of each other

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

How to determine if two strings are permutations of each other

30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 08:54

    If we do the initial length check, to determine if the two strings are of the same length or not,

        public boolean checkIfPermutation(String str1, String str2) {
          if(str1.length()!=str2.length()){
            return false;
          }
          int str1_sum = getSumOfChars(str1);
          int str2_sum = getSumOfChars(str2);
          if (str1_sum == str2_sum) {
            return true;
          }
          return false;
    }
    
    public int getSumOfChars(String str){
          int sum = 0; 
          for (int i = 0; i < str.length(); i++) {
            sum += str.charAt(i);
          }
          return sum;
    }
    

提交回复
热议问题