贪心思想:种花

Input: flowerbed = [1,0,0,0,1], n = 1 Output: True

应用指针的思想,注意判断边界的条件

class Solution {
    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        /*
        利用三个指针:当前节点,前一个节点,后一个节点,
        如果当前节点的前、后节点都为0;表示当前节点可以种花,值为1
        注意判断当前节点是数组第一位和最后一位
        只需要他的后一个节点或者前一个节点是0即可
        */
        int len=flowerbed.length;
        int cnt=0;
        for(int i=0;i<len;i++){
            if(flowerbed[i]==1){
                continue;
            }
            int pre=i==0?0:flowerbed[i-1];
            int next=i==len-1?0:flowerbed[i+1];
            if(pre==0&&next==0){
                cnt++;
                flowerbed[i]=1;
            }
        }
        return cnt>=n;
    }
}
如果能够查找,就继续查找,一旦找不到,立马返回错误
s = "abc", t = "ahbgdc"
Return true.
class Solution {
    public boolean isSubsequence(String s, String t) {
        /*
        在S中查找T中字符第一次出现的位置,如果查到,
        就查找下一个t中的字符,查找不到直接返回false
        */
        int index=-1;
        for(char c : s.toCharArray()){
            index = t.indexOf(c, index + 1);
            if(index==-1){
                return false;
            }
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_31957639/article/details/84099556