Given a string str, write a Java program to print all words with even length in the given string. Examples:
Input: s = "This is a java language"
Output: This
is
java
language
Input: s = "i am GFG"
Output: am
Approach:
- Take the string
- Break the string into words with the help of split() method in String class. It takes the string by which the sentence is to be broken. So here ” “(space) is passed as the parameter. As a result, the words of the string are split and returned as a string array
String[] words = str.split(" ");
for(String word : words)
{ }
int lengthOfWord = word.length();
- If the length is even, then print the word.
Below is the implementation of the above approach:
Java
class GfG {
public static void printWords(String s)
{
for (String word : s.split( " " ))
if (word.length() % 2 == 0 )
System.out.println(word);
}
public static void main(String[] args)
{
String s = "i am Geeks for Geeks and a Geek" ;
printWords(s);
}
}
|
Time complexity: O(n) where n is length of given string
Auxiliary Space: O(1)
Approach 2: Using Dynamic Programming:
In this approach, we split the string into words and store the length of each word in an array. Then, we loop through the array and check if the length of each word is even. If it is, we print the word. This approach uses dynamic programming to store the length of each word in an array, which can be reused in subsequent loops, reducing the overall number of calculations. However, in practice, the difference in performance between this approach and the original approach is likely to be negligible.
Here is the DP approach in Java:
Java
class GfG {
public static void printWords(String s) {
String[] words = s.split( " " );
int [] wordLengths = new int [words.length];
for ( int i = 0 ; i < words.length; i++) {
wordLengths[i] = words[i].length();
}
for ( int i = 0 ; i < words.length; i++) {
if (wordLengths[i] % 2 == 0 ) {
System.out.println(words[i]);
}
}
}
public static void main(String[] args) {
String s = "i am Geeks for Geeks and a Geek" ;
printWords(s);
}
}
|
Output:
am
Geek
Time complexity: O(n) where n is length of given string
Auxiliary Space: O(n) where n is the total number of characters in the input string.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
18 Mar, 2023
Like Article
Save Article