Simple Java O(n) solution using HashSet


  • 0
    J
    import java.util.*;
    
    public class Solution {
    
    	public List<String> findRepeatedDnaSequences(String s) {
    		List<String> result = new ArrayList<>();
    		if (s == null || s.trim().isEmpty()) {
    			return result;
    		}
    		Set<String> repeated = new HashSet<String>();
    		findReptSqns(s, repeated, result);
    		return result;
    	}
    
    	private void findReptSqns(String s, Set<String> repeated, List<String> result) {
    		for (int i = 0; i < s.length()-9; i++) {
    				String tmp = s.substring(i, i + 10);
    				if (!repeated.add(tmp) && !result.contains(tmp)) {
    					result.add(tmp);
    				}
    		}
    
    	}
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.