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. :)
(open source and trusted by devs everywhere ❤️)