Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class TitleFinder {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- // Read the title string
- String title = scanner.nextLine();
- // Read the number of lines
- int n = Integer.parseInt(scanner.nextLine());
- // Loop through the lines
- for (int i = 0; i < n; i++) {
- // Read the current line
- String line = scanner.nextLine();
- // Check if the line is a subsequence of the title
- if (isSubsequence(line, title)) {
- // Remove the line from the title
- title = removeSubsequence(line, title);
- // Print the modified title
- System.out.println(title);
- } else {
- // Print a message
- System.out.println("No such title found!");
- }
- }
- }
- // A helper method to check if a string is a subsequence of another string
- public static boolean isSubsequence(String s1, String s2) {
- // Initialize two pointers for s1 and s2
- int i = 0;
- int j = 0;
- // Loop until one of the strings is exhausted
- while (i < s1.length() && j < s2.length()) {
- // If the characters match, move both pointers forward
- if (s1.charAt(i) == s2.charAt(j)) {
- i++;
- j++;
- } else {
- // Otherwise, move only the pointer for s2 forward
- j++;
- }
- }
- // Return true if all characters of s1 are matched
- return i == s1.length();
- }
- // A helper method to remove a subsequence from a string
- public static String removeSubsequence(String s1, String s2) {
- // Initialize a string builder to store the result
- StringBuilder sb = new StringBuilder();
- // Initialize two pointers for s1 and s2
- int i = 0;
- int j = 0;
- // Loop until one of the strings is exhausted
- while (i < s1.length() && j < s2.length()) {
- // If the characters match, skip them and move both pointers forward
- if (s1.charAt(i) == s2.charAt(j)) {
- i++;
- j++;
- } else {
- // Otherwise, append the character from s2 to the result and move only the pointer for s2 forward
- sb.append(s2.charAt(j));
- j++;
- }
- }
- // Append the remaining characters from s2 to the result
- sb.append(s2.substring(j));
- // Return the result as a string
- return sb.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement