Program opened below. You can scroll through the algorithm, Java code and output.

Words Containing the Last Shortest Word

Download .java

Question

Input a sentence, identify the final occurrence of a shortest word, and display every word containing that word as a substring.

Step 1: Start the program. Step 2: Read the input sentence. Step 3: Remove excess spaces at both ends. Step 4: Split the sentence into words at one or more spaces. Step 5: Take the first word as the shortest candidate. Step 6: Scan each word in its original order. Step 7: Compare the candidate length with the current word length. Step 8: Replace the candidate whenever a shorter word is found. Step 9: Also replace it when the lengths are equal, retaining the last shortest word. Step 10: Display the original sentence. Step 11: Display the selected shortest word. Step 12: Visit the words once more. Step 13: Search each word for the selected shortest word. Step 14: Display every word containing that sequence of characters. Step 15: Stop.
Java
import java.util.*;
class ShortestContained {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine().trim();
        String[] words = s.split(" +");
        String shortest = words[0];
        for (String word : words) {
            if (word.length() <= shortest.length()) {
                shortest = word;
            }
        }
        System.out.println("Sentence: " + s);
        System.out.println("Last shortest word: " + shortest);
        for (String word : words) {
            if (word.indexOf(shortest) >= 0) {
                System.out.println(word);
            }
        }
    }
}
Input: at cat bat Output: Last shortest word: at / at / cat / bat
← Previous Program 17 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.