Untitled

 avatar
unknown
plain_text
9 months ago
2.2 kB
13
Indexable
package LogicalProblems;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;

public class FirstndLast {

    /**
     *This calss takes a string text and an array of strings words, return an array of all index pairs [i, j] so that the substring text[i...j] is in words.
     * Return the pairs [i, j] in sorted order (i.e., sort them by their first coordinate, and in case of ties, sort them by their second coordinate).
     *
     * Examples:
     * Input: text = "codingisfun", words = ["code", "fun", "is"]
     * Output: [[6,7],[8,10]]
     * Explanation:
     *
     * "is" is found at index [6,7]
     * "fun" is found at index [8,10]
     * Input: text = "programmingrocks", words = ["pro", "rock", "ram", "ing"]
     * Output: [[0,2],[4,6],[7,9],[11,14]]
     *
     * Explanation:
     * "pro" is found at index [0,2]
     * "ram" is found at index [4,6]
     * "ing" is found at index [7,9]
     * "rock" is found at index [11,14]
     */

    public static List<int[]> indexPairs(String text, String[] words) {
        int[] index = new int[2];
        List<int[]> pairs = new ArrayList<>();

        for (int i = 0; i < words.length; i++) {
            int startIndex = text.indexOf(words[i]);
            if (startIndex != -1) {
                index[0] = startIndex;
                index[1] = startIndex + words[i].length() - 1;
                pairs.add(index);
                index = new int[2];
            }
        }

        return pairs;
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);

        System.out.println("Enter the text:");
        String text = s.nextLine();

        System.out.println("Enter number of words:");
        int n = s.nextInt();
        s.nextLine();

        String[] words = new String[n];
        System.out.println("Enter the words:");
        for (int i = 0; i < n; i++) {
            words[i] = s.nextLine();
        }

        List<int[]> result = indexPairs(text, words);

        for (int i = 0; i < result.size(); i++) {
            int[] pair = result.get(i);
            System.out.println("[" + pair[0] + ", " + pair[1] + "]");
        }
    }
}
Editor is loading...
Leave a Comment