一个字符串的字符从新排序后,可否变成另一个字符

package cglib;java

import java.util.Arrays;
import java.util.HashMap;数组

public class StringNumber {
    
    public static void main(String args[]) throws Exception{
        
        String str0="123456";
        String str1="654322";
        System.out.println("结果1、:"+checkSam(str0,str1));
        System.out.println("结果二:"+permutation2(str0,str1));
        System.out.println("结果三:"+check(str0,str1));
        
    }
    
public static boolean checkSam(String stringA, String stringB) {
        
        boolean result = false;
        //先判断两个字符串长度是否相同,若是不相同直接返回flase
        if (stringA.length() != stringB.length()) {
            return result;
        } else {
            //若是两个字符串长度相同将他们转化为数组并排序,最后比对数组中对应位置的值是否相等,若是所有相等则返回true,不然放回false
            String[] a = stringA.split("");
            String[] b = stringB.split("");
            
            Arrays.sort(a);            //利用了数组的排序方法
            Arrays.sort(b);
            
            
           // 或者直接
           return Arrays.equals(a, b);   //注意使用Arrays.equals(c1, c2)而不是c1.equals(c2):若是两个数组以相同顺序包含相同的元素,则两个数组是相等的
        排序

    
          /*  for (int i = 0; i<a.length; i++) {
                if (a[i].equals(b[i])) {                    //这里只能使用equals方法而不能使用==
                    System.out.println(a[i]+"  "+b[i]);
                    continue;
                } else {
                    return result;
                }
            }
            return result = true; */           
        }     
    }rem

public static boolean permutation2(String s,String t){
    if(s.length() != t.length())
        return false;
    int[] letters = new int[256];
    char[] s_array = s.toCharArray();
    for(char c : s_array)
        letters[c]++;
    for(int i = 0;i<t.length();i++){
        int c = (int)t.charAt(i);
        if(--letters[c] < 0)
            return false;
    }
    return true;
}
public static boolean check(String stringA, String stringB) {
    char[] arra = stringA.toCharArray();
    HashMap<Character,Integer> hm = new HashMap<>();
    for(char c : arra){
        if(!hm.containsKey(c)){
            hm.put(c, 1);
        }else{
            hm.put(c,hm.get(c)+1);
        }
    }
     
    char[] arrb = stringB.toCharArray();
    for(char b : arrb){
        if(hm.containsKey(b)){
            hm.remove(b);
        }
    }
    return hm.isEmpty();
}
    }
    字符串

相关文章
相关标签/搜索