[LeetCode- interview 01.02] each other to determine whether the character rearrangement

A. Title Description

Given two strings s1 and s2, Write a program, which determines the character of a string rearranging, you can become a another string.

示例 1:
输入: s1 = "abc", s2 = "bca"
输出: true 

示例 2:
输入: s1 = "abc", s2 = "bad"
输出: false

说明:
0 <= len(s1) <= 100
0 <= len(s2) <= 100

II. Explanations

1. Method One:

(1) problem-solving ideas:

  • Now s1, s2 string into an array of characters c1, c2
  • Then array c1, c2 sort
  • Then arrays c1, c2 converted to a string
  • Reuse equal function compares two strings are identical to

(2) Java code to achieve:

public boolean CheckPermutation(String s1, String s2) {
        //1.将字符串转换成数组
        char[] charArray1 = s1.toCharArray();
        char[] charArray2 = s2.toCharArray();

        //若两个字符串的长度不同,则肯定不能重排
        if(s1.length() != s2.length()){
            return false;
        }

        //给数组排序
        Arrays.sort(charArray1);
        Arrays.sort(charArray2);

        //将数组重新转换为字符串
        String c1 = String.copyValueOf(charArray1);
        String c2 = String.copyValueOf(charArray2);

        //比较两个字符串是否相等
        if(c1.equals(c2)){
            return true;
        }else{
            return false;
        }
}
Published 18 original articles · won praise 0 · Views 476

Guess you like

Origin blog.csdn.net/aflyingcat520/article/details/105331927