Find longest word in a given string but the word only have even length | SoloLearn: Learn to code for FREE!


Find longest word in a given string but the word only have even length

if input is "today is a good day" then output is "good" because it has even length and longest even word

11/6/2017 5:21:24 AM


5 Answers

New Answer


I won't write this for you because I think it's best for people to learn by practice, but this is an algorithm for the problem Input: string 1) Split the string by spaces 2) Check each word in the split string array a) if length not even skip b) otherwise compare to the current largest word (initialize to an empty string)


Mohan why are your questions always urgent


it's exercise to do and I am very thankful ... thank you Ace


I was asked this question in Bloomberg Software Engineer Interview. The one modification I can suggest is rather than splitting with space, traverse character by character until you encounter space. Form words from the interval of previous and current space. This way you will not store a big array in storage. This concern was pointed out by my interviewer as I split the string and he told me that consider a case where the input string is too large or real-time input stream then how this will impact and hence I corrected my solution with traversal character by character. Hope this helps.


public class LongestEven { public static void Long(String Str) { String[] strarray = Str.split(" "); String Evenword=""; for(String st : strarray) { if(st.length()%2==0) { if(Evenword.length()<st.length()) { Evenword=st; } } }System.out.print("Word is an Even and is " +Evenword); } public static void main(String args[]) { Long(" abababababab I AM SHSHSHSHS KAM "); } }