一個字符串的字符從新排序後,可否變成另一個字符

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();
}
    }
    字符串

相關文章
相關標籤/搜索