CI1.3 给定两个字符串,确定一个字符串重新排列后,能否变成另一个字符串

来源:互联网 发布:android精美界面源码 编辑:程序博客网 时间:2024/06/10 06:04

问题分析

  1. 首先确认变位词是否区分大小写【此次区分大小写】
  2. 确认是否要考虑空白字符

优化: 比较两个字符串时,只要长度不同,就不可能是变位词。

解法一:排序字符串

对两个变位词的字符的字符进行排序,然后比较排序后的字符串。
【注】非最优,但是简单易懂,通用

import java.util.Arrays;public class Main {    public static void main(String[] args) {        String s = "qwerzsdf htlo21234";        String t = "21234qw erzsdfhtlo";        System.out.println(permutation(s, t));    }    public static boolean permutation(String s, String t) {        if (s.length() != t.length()) {            return false;        }        return sort(s).equals(sort(t));    }    public static String sort(String s) {        char[] content = s.toCharArray();        Arrays.sort(content);        return new String(content);    }}

解法二:检查两个字符串的各字符数是否相同

遍历字母表,计算每个字符出现的次数,然后比较这两个数组。
【注】需要核实字符集的大小,此处假设字符集为ASCII

public class Main {    public static void main(String[] args) {        String s = "qwerz sdfhtlo21234";        String t = "21234qw erzsdfhtlo";        System.out.println(permutation(s, t));    }    public static boolean permutation(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;    }}

0 0
原创粉丝点击