I’ve decided to begin a series that I plan to finish within one week, involving data structures, algorithms, object oriented programming paradigms as well as web scalability principles (and more). In this first part, I’ll be looking at arrays, strings and the problems that might arise when dealing with them.

First, arrays and strings can pretty much be considered to be the same data structure for the most part. As we all know, an array is a list of fixed length. For example:

arrayOfFruit = ["apple", "peach", "banana", "grapes"];

This is pretty clearly, a list of fruits that are strings. As you can see, there are 4 elements in the array and we can iterate over them as we would expect.

stringOfFruits = "apple peach banana grapes";

This, is clearly an a string containing the same components of the array above. Just like the array, we can iterate over the string using the spaces as a divider. And, just like the array, we get the same results out of our iteration. Therefore, from here on in, we’re going to treat each of the data structures the same as the other.

Let’s take a look at an example question involving a string:

Develop an algorithm to figure out whether a string is a palindrome (the same frontwards as it is backwards). An example of a palindrome is the string: ‘racecar’

First, we’re going to create a stack of Characters. Not sure what a stack is? That’s what part 3 is for!

String frontwards = "racecar";

Stack<Character> stack = new Stack<>();

for(int i = 0; i < frontwards.length; i++){

    stack.push(frontwards.charAt(i));

}

Now we have the string, stored character by character in the stack. The next step is to construct the string again, backwards, by popping characters off the stack and appending them onto a resultant string.

String backwards = "";

while(!stack.empty()){

    backwards =+ Character.toString(stack.pop());

}

Now we just check for equality.

if(backwards.equals(frontwards)){

    return (frontwards + " is a palindrome");

} else {

    return (frontwards + " is NOT a palindrome");

}

And that’s all there is to it! In order to tackle these problems, we need to thing in data structures and algorithms. This was just a taste of how to go about solving odd problems – and there’s more to come!

Part 2 will contain LinkedLists!

 

Advertisements