5386.检查一个字符串是否可以打破另一个字符串

image-20200503195857973

解题

思路

  • 首先两个字符串长度都相等,无后顾之忧。
  • 将两个数组分别装入两个List集合,调用Collections.sort(list)进行排序,得到集合l1,l2。
  • 若要满足要求,要么 l1 的元素都小于等于 l2 ,要么 l1 的元素大于等于 l2。
  • 通过用例 161ms

代码

 public boolean checkIfCanBreak(String s1, String s2) {
        boolean ans=false;
        char[] chars = s1.toCharArray();
        char[] chars1 = s2.toCharArray();
        List<Character> l1= new ArrayList<>();
        List<Character> l2= new ArrayList<>();
        for(char c:chars){
            l1.add(c);
        }
        for(char c:chars1){
            l2.add(c);
        }
        Collections.sort(l1);
        Collections.sort(l2);
        int count=0;
        for(int i=0;i<s1.length();i++){
            if(l1.get(i)>=l2.get(i)){
                ans=true;
                count++;
            }else{
                ans=false;
                break;
            }
        }
        if(count==s1.length()){
            return true;
        }
        for(int i=0;i<s1.length();i++){
            if(l1.get(i)<=l2.get(i)){
                ans=true;
            }else{
                ans=false;
                break;
            }
        }
        return ans;
    }

优化

思路

  • 在上面思路的基础上,将集合排序改成更直接的数组排序

    Collections.sort(list) ---> Arrays.sort(list)

  • 时间复杂度取决于排序的方式

  • 结果 10ms

代码

 public boolean checkIfCanBreak2(String s1, String s2) {
        boolean ans=false;
        char[] chars1 = s1.toCharArray();
        char[] chars2 = s2.toCharArray();
        Arrays.sort(chars1);
        Arrays.sort(chars2);
        int count=0;
        for(int i=0;i<s1.length();i++){
            if(chars1[i]>=chars2[i]){
                ans=true;
                count++;
            }else{
                ans=false;
                break;
            }
        }
        if(count==s1.length()){
            return true;
        }
        for(int i=0;i<s1.length();i++){
            if(chars1[i]<=chars2[i]){
                ans=true;
            }else{
                ans=false;
                break;
            }
        }
        return ans;
    }

原文地址:https://www.cnblogs.com/yh-simon/p/12823218.html