1. 程式人生 > >貪心思想:種花

貪心思想:種花

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;
    }
}