Note- This particular problem can be solved in different techniques but here i am going to use the optimal solution in terms of memory and efficiency.
Algorithum- step 1- First is will reverse the every word given in our String
step 2- Then i will reverse the whole String.
step 3- Get the desire output.
public class Problem8 {
static StringBuffer s = new StringBuffer("Kushwaha Umesh is name My");
static void swap(int i, int j) { //This method will reverse the String
while (i < j) {
char c = s.charAt(i);
s.setCharAt(i, s.charAt(j));
s.setCharAt(j, c);
i++;
j--;
}
}
public static void main(String args[])
{
System.out.println(s);
int n = 0, l = 0, m = 0;
while (n < s.length())
{
if (n == 0) {
l = 0;
}
if (s.charAt(n) == ' ' || n == s.length() - 1) {
m = n;
//With the help of this condition we can //recognize particular word in given String.
if (n == s.length() - 1)
{
m = n;
} else
{
m--;
}
swap(l, m); //Here we will get the final output.
l = n + 1;
}
n++;
}
System.out.println(s);
swap(0, s.length() - 1);
System.out.println(s);
}
}
Algorithum- step 1- First is will reverse the every word given in our String
step 2- Then i will reverse the whole String.
step 3- Get the desire output.
public class Problem8 {
static StringBuffer s = new StringBuffer("Kushwaha Umesh is name My");
static void swap(int i, int j) { //This method will reverse the String
while (i < j) {
char c = s.charAt(i);
s.setCharAt(i, s.charAt(j));
s.setCharAt(j, c);
i++;
j--;
}
}
public static void main(String args[])
{
System.out.println(s);
int n = 0, l = 0, m = 0;
while (n < s.length())
{
if (n == 0) {
l = 0;
}
if (s.charAt(n) == ' ' || n == s.length() - 1) {
m = n;
//With the help of this condition we can //recognize particular word in given String.
if (n == s.length() - 1)
{
m = n;
} else
{
m--;
}
swap(l, m); //Here we will get the final output.
l = n + 1;
}
n++;
}
System.out.println(s);
swap(0, s.length() - 1);
System.out.println(s);
}
}
Output:
Kushwaha Umesh is name My
ahawhsuK hsemU si eman yM //step 1
My name is Umesh Kushwaha //step 2
|
No comments:
Post a Comment