Browsing the archives for the String Manipulation category

Implement strstr

Question: Implement strstr in Java. Find the first instance of a string in another string. Answer: public int Search(String haystack, String needle){ for(int i = 0; i < haystack.length(); i++ ) { for(int j = 0; j < needle.length() && i+j < haystack.length(); j++ ) { if(needle.charAt(j) != haystack.charAt(i+j)) { break; } else if (j […]

Combinations of a String

Question: Write an algorithm to print all possible combinations of characters in a string. Answer: Any thoughts? One thing is for sure, we can definitely use some recursive logic here. Let’s approach this problem methodically. Since we need to generate combinations, we can start with a single character and then continue to add a character […]

First Non-Repeated Character

Question: Write an algorithm to find the first non-repeated character in a string. For example, the first non-repeated character in the string ‘abcdab’ is ‘c’. Answer: Seems trivial enough right? If a character is repeated, we should be able to search the string to determine if that character appears again. So if we go about […]

Anagrams in an Array of Strings

Question: You are given an array of strings and you are asked to display all the anagrams within the array. For those who don’t know, two words are anagrams if they contain the same characters. Answer: The brute force solution would be to take each string and compare it to every other string in the […]

Permutations of a String

Question: Print all the permutations of a string. Write code in C. Answer: Here is a recursive solution to print all the permutations of a string. However, this solution does not take care of duplicates. It is assumed that there are no duplicates in the string. I left out the implementation of the swap method […]

Reverse the Order of Words in a String

Question: Reverse the order of words in a string in C using as little additional memory as possible. Answer: The solution for this questions uses the solution of Reverse a String. I am going to make a small change to that solution by adding a length parameter. It will probably be better for you to […]

Reverse a String

Question: Reverse a string in C using as little additional memory as possible. Answer: The first solution needs the size of a char and size of two integers, all of which will be allocated from the stack. This solution is the most commonly accepted “good” solution. Here is the code. void reverseString(char* str) { int i, […]