An algorithm to resolve γ-rays from charged cosmic rays with DAMPE