## find longest word in the sentence

### Find the longest word in the sentence

I am using `javascript` for this question.

It can be done in a lot of ways. The straight forward way could be the fastest probably. You will loop over the array of the words – you can split it with space – ” “.

Then just compare the value of the word length with maximum value and overwrite when it is higher – you know what I mean..

I will show the single liner for this though

``````
var longestWord = "Guess what the longest word in the dictionary is".split(" ").sort(function(a, b){
return b.length - a.length;
})[0];
```
```

Let’s go through what is going on..

The first part `"Guess what the longest word in the dictionary is"` is the given example sentence we are trying to find the longest word for.

Then we split the string into array of words using the `split(" ")` function. Now we have array to work with.

Then we sorted the array with sorter function passed to it. Sorter function in this one is anonymous function that we pass to it.

Finally we just took the first element of the sorted array which is sorted by the length of the word.

Also with the same concept, we have have it using reduce function;

``"I still am having the wonderfulness of this thing ".split(" ").reduce((word1, word2) => word2.length > word1.length ? word2 : word1 );``

That is it!

## Find longest palindrom from sequence of characters

### Given the string, find the longest palindrom you can form from it

``````
/**
* @author gullele.com
*/
public class LongestPalindrom {
public static void main(String[] args) {
LongestPalindrom longest = new LongestPalindrom();
System.out.println(longest.longest("zzbmbmbdmm"));
}

public String longest(String string) {
if (string.length() == 0 || string == null) {
return "";
}

StringBuffer palindrom = new StringBuffer();
Map charBag = new HashMap();
for (Character c : string.toCharArray()) {
int totalChar = charBag.get(c) != null ? charBag.get(c) : 0;
if ((totalChar + 1) % 2 == 0) {
palindrom.append(c);
palindrom = palindrom.insert(0, c);
charBag.remove(c);
continue;
}
charBag.put(c, ++totalChar);
}

if (charBag.size() > 0) {
Iterator it = charBag.entrySet().iterator();
Map.Entry pair = (Map.Entry)it.next();
String c = pair.getKey().toString();
palindrom.insert(palindrom.length()/2, c);
}
return palindrom.toString();
}
}

``````