I wrote couple of posts previously here and here on how to find duplicates in an array and we saw different variety of that problem. I want to switch gear now to string related problems. Previous posts on arrays built a good foundation for us to solve string related problem because string is an essentially an array of characters.
We are given a word which contains only alphabetical characters. Considering string is an array of characters and one of the biggest advantage and vital key to solve certain array problems is to iterate an array from forwards and backwards at the same time.
We can use two pointers where one pointer start from beginning and other pointer move inwards from end of the array.
This information is vital to solve this problem. Let’s use that algorithm and write down code.
Could we use the same algorithm to reverse words inside a sentence? e.g. "This is a word" should change into "word a is This" by the algorithm.
If we split the string by a whitespace we'll get an array of strings and then we can use above algorithm to reverse a sentence.
Another problem where we could utilize same algorithm is to solve string palindrome problem. A word is a palindrome when it reads same from backwards as forward e.g. kayak, noon etc.
Now we know that we can traverse a string from forwards and backwards, we can use that knowledge to solve palindrome problem.
This is it for this post. I plan to write more on string related problems in my next posts.
Stay tuned. :)
Top comments (8)
very , very small optimization :p
if by any chance you can benchmark the 2 versions : me very glad ;)
JavaScript!!
Go! This was a fun challenge as I'm fairly new to Go =) Feedback is welcomed!
Python!!
Here’s a challenge for you. You wrote the same loop twice. Could you write a function that takes an anonymous function as an arg so you never have to write this “dual ended” loop again?
why not just this
public static boolean isPalindrome(String str) {
return str.equals(new StringBuilder(str).reverse().toString());
}
You are using Java's in built reverse method. Normally in an interview, you create your own algorithm i.e. your own implementation of reverse method.
Oh OK these post are like examples for juniors when doing interview and stuff