LeetCode210404赎金信(小串是否均包含在大串中)和字符串的单词数

赎金信

public static boolean method(String smallStr,String bigStr){
    
    

       int[] start = new int[26];
       for (char small : smallStr.toCharArray()) {
    
    
           // small为char,为什么使用的是indexOf(int ch寻找的字符,int Fromindex开始寻找的位置)呢? 因为小杯子可以放进大盒子。
           int index = bigStr.indexOf(small,start[small-'a']);

           if (index == -1) {
    
    
               return false;
           }

           // 保存开始寻找的位置(即当前找到的字符的下一个位置)
           start[small-'a'] = index+1; // 保存找到字符的下一个字符,作为开始字符索引

       }

       return true;
   }

字符串的单词数

public static int method1(String s) {
    
    

        String trim = s.trim();
        if (trim.equals("")) {
    
    
            return 0;
        }
        String[] s1 = trim.split("\\s+");
        return s1.length;
    }

    public static int method2(String s) {
    
    

        int n = s.length();
        int count = 0;
        for (int i = 0; i < n; i++) {
    
    

//            这里i==0必须放在前面,为此题精华,若为初始字符,则count必加一
            if ( (i == 0||s.charAt(i-1) == ' ') && s.charAt(i) != ' ') {
    
    
                count++;
            }
        }
        return count;
    }

猜你喜欢

转载自blog.csdn.net/m0_47119598/article/details/115429841
今日推荐