priti2.jain
BAN USER- 1of 1 vote
AnswersReverse String Ex: "Hello World" into "World Hello"
- priti2.jain in United States| Report Duplicate | Flag | PURGE
McAfee Applications Developer Algorithm
public static void findFifthElementFromEnd() {
if (linkedList == null && linkedList.head == null) {
return;
}
Node fast, slow;
int i = 0;
fast = slow = linkedList.head;
while (fast != null && i < 5) {
fast = fast.next;
i++;
} // now fast reach to 5th location.
if (i < 4) {
System.out
.println("Linkedlist has less than 5 elements");
return;
}
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
System.out.println("5th element from end is :" + slow.data.toString());
}
public static void reverse(String input)
{
String[] words = input.split(" ");
int length = words.length;
StringBuilder finalString = new StringBuilder(input.length());
for(int i=length-1;i >= 0;i--)
{
finalString.append(words[i]);
finalString.append(" ");
}
System.out.println("Result String: "+ finalString.toString());
}
Input : Hello World
Output : World Hello
Yes, you are right.
- priti2.jain August 18, 2013Internally, it(split method) uses a 2 pass routine. In the first pass, the index of the separator characters are discovered and stored. In the second pass, the string is "split" by calling Substring repeatedly and storing the results in an output array using the indices previously saved.
As such, the algorithm is effectively O(N), since it's doing linear passes through the input string.