*Flower Bed

/*Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die. Given a flowerbed (represented as an array containing booleans), return if a given number of new flowers can be planted in it without violating the no-adjacent-flowers rule 
Sample inputs 

Input: 1,0,0,0,0,0,1,0,0 

3 => true 
4 => false 
Input: 1,0,0,1,0,0,1,0,0 

1 => true 
2 => false 
input: 0 

1 => true 
2 => false */ 

public boolean canPlaceFlowers(List<Boolean> flowerbed, int numberToPlace) { 

// Implementation here 
}

import java.util.ArrayList;
public class solution{
public static boolean canPlaceFlowers(ArrayList<Boolean> arr, int count) {

     if(arr == null){
        throw new NullPointerException();
    }
    
    if(count>arr.size()) return false;
    
    if(arr.size()==1)
    {
        if(!arr.get(0))return true;
        else return false;
    }
         
    
    if(arr.size()==2)
    {
        if(count<=1&&!arr.get(0)&&!arr.get(1))return true;
        else return false;  
    }

    int locations = 0;
    boolean lastPos=arr.get(0), thisPos=arr.get(0), nextPos=arr.get(0);
    int index = 2;
    while(index < arr.size()){
        lastPos = arr.get(index-2);
        thisPos = arr.get(index-1);
        nextPos = arr.get(index);
        if(!(lastPos || thisPos || nextPos)){
            arr.set(index-1,true);
            locations ++;
            if(locations >= count){
                return true;
            }
        }

        index++;
    }

    if(index == arr.size() && !(thisPos || nextPos)){
        locations++;
    }
    return locations >= count;
    
}

  public static void main(String[] args) {
        ArrayList<Boolean> list = new ArrayList<Boolean>();
        list.add(false);
        int no = 1;
    boolean res = canPlaceFlowers(list,no);
    System.out.println(res);
    }

}

reference:

http://www.careercup.com/question?id=5119852580700160

原文地址:https://www.cnblogs.com/hygeia/p/5154534.html