method updated to stop looping when lcs is end of string