Leetcode-字符串刷题记录

520. 检测大写字母

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public boolean detectCapitalUse(String word) {
        int i = 0;
        char[] arr = word.toCharArray();
        int up = 0, low = 0;
        while(i < arr.length){
            if(arr[i] >= 'a'){
                low++;
            }else{
                up++;
            }
            i++;
        }
        if(up == arr.length) return true;
        if(low == arr.length) return true;
        if(up == 1 && arr[0] < 'a') return true;
        return false;
    }

125. 验证回文串

经典问题,需要过滤非字符非数字。

Leetcode-数组刷题记录

数组的遍历

485. 最大连续1的个数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public int findMaxConsecutiveOnes(int[] nums) {
        //res存储最长的子数组
        int res = 0;
        //count记录的是每个被0隔断的子数组
        int count = 0;
        for(int i = 0; i < nums.length; i++){
            //如果当前元素是1,更新当前子数组的长度
            if(nums[i] == 1){
                count++;
            }else {
                //遇到0,比较res, count的大小,并将count重置为0
                res = Math.max(res, count);
                count = 0;
            }
        }
        //避免最后一个子数组是最大的情况,例如:1,0,1,1,0,1,1,1,1
        return Math.max(res, count);
    }

495. 提莫攻击

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public int findPoisonedDuration(int[] timeSeries, int duration) {
        int res = 0;
        for(int i = 0; i < timeSeries.length; i ++){
            //当前能持续的时间
            int time = timeSeries[i] + duration -1;
            //超过下一次攻击的时间
            if(i != timeSeries.length -1 && time >= timeSeries[i + 1]){
                res += (timeSeries[i + 1] - timeSeries[i]);
            }else{
                res += duration;
            }
        }
        return res;
    }

第三大的数

时间复杂度要求$O(n)$,也就是只能通过一趟遍历完成。

0%