zoukankan      html  css  js  c++  java
  • 判断两个字符串是否由相同的字符组成

    描述

    判断两个字符串是否由相同的字符组成

    分析

    方法一,排序法。对两个字符串进行排序,然后在比较。

    方法二,空间换时间。ascII字符共256个,对字符串1出现的字符在对应的数组里加1,对字符串1出现的字符在对应的数组里减1。

    代码

    方法一 排序法。

    public class Test {
        public static boolean compare(String s1,String s2){
            if(s1.length()!=s2.length()) return false;
            byte[] byte1=s1.getBytes();
            byte[] byte2=s2.getBytes();
            Arrays.sort(byte1);
            Arrays.sort(byte2);
            for(int i=0;i<s1.length();i++){
                if(byte1[i]!=byte2[i]) return false;
            }
            return true;
        }
    
        public static void main(String[] args) {
            System.out.println(compare("zayyyy","zayyyy"));
        }
    }

    方法二,空间换时间。

    public class Test {
        public static boolean compare(String s1,String s2){
            if(s1.length()!=s2.length()) return false;
            byte[] byte1=s1.getBytes();
            byte[] byte2=s2.getBytes();
            int[] charCount=new int[256];  //ascII 字符共有266个。
            for(int i=0;i<s1.length();i++){
                charCount[byte1[i]]++;
                charCount[byte2[i]]--;
            }
            for(int i:charCount){
                if(i!=0) return false;
            }
            return true;
        }
        public static void main(String[] args) {
            System.out.println(compare("zayyyy","zayyyb"));
        }
    }
  • 相关阅读:
    从进入这里,没有写过什么文章,现在开始吧
    24)
    23)
    22)
    21)
    20)
    19)
    18)
    17)
    16)
  • 原文地址:https://www.cnblogs.com/zadomn0920/p/6358255.html
Copyright © 2011-2022 走看看