An intruder caught in the grounds of Buckingham Palace twice in four days had tried to break in a month before, a court has heard.