Untitled
import java.util.*; public class Solution { public List<String> findRepeatedDnaSequences(String s) { int n = s.length(); if (n <= 10) return new ArrayList<>(); Set<String> seen = new HashSet<>(); Set<String> repeated = new HashSet<>(); // Initialize StringBuilder with the first 10 characters StringBuilder currentWindow = new StringBuilder(s.substring(0, 10)); // Add the initial substring to the seen set seen.add(currentWindow.toString()); for (int i = 10; i < n; i++) { // Slide the window by removing the first character and adding the next character currentWindow.deleteCharAt(0); currentWindow.append(s.charAt(i)); // Convert the current window to a string and check for repetition String windowString = currentWindow.toString(); if (!seen.add(windowString)) { repeated.add(windowString); } } return new ArrayList<>(repeated); } }
Leave a Comment