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"));
        }
    }
  • 相关阅读:
    密码保护
    实现搜索功能
    完成个人中心—导航标签
    个人中心标签页导航
    评论列表显示及排序,个人中心显示
    完成评论功能
    从首页问答标题到问答详情页
    首页列表显示全部问答,完成问答详情页布局
    Android基础学习:Android环境搭建
    liunx 硬盘分区
  • 原文地址:https://www.cnblogs.com/zadomn0920/p/6358255.html
Copyright © 2011-2022 走看看