A characterization of stable and Borel ideals