判断两个字符串是否由相同的字符组成
生活随笔
收集整理的這篇文章主要介紹了
判断两个字符串是否由相同的字符组成
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
描述
判斷兩個字符串是否由相同的字符組成
?
分析
方法一,排序法。對兩個字符串進行排序,然后在比較。
方法二,空間換時間。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"));} }?
轉載于:https://www.cnblogs.com/zadomn0920/p/6358255.html
總結
以上是生活随笔為你收集整理的判断两个字符串是否由相同的字符组成的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: macbook excel导入html,
- 下一篇: wifi服务器无响应如何修复,wifi打