forked from joharbatta/DataStructure-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseWords.java
More file actions
62 lines (56 loc) · 1.47 KB
/
ReverseWords.java
File metadata and controls
62 lines (56 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.Scanner;
import java.util.Stack;
public class ReverseWords{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
String str = s.nextLine();
reverseWords(str);
reverseWords1(str);
}
static void reverseWords1(String s)
{
String[] words=s.split("\\s");
StringBuilder d=new StringBuilder();
// String result="";
for(int i=0;i<words.length;i++)
{
String reverse="";
String k=words[i];
int n=k.length()-1;
for(int p=n;p>=0;p--)
{
reverse = reverse + k.charAt(p);
}
//words[i]=reverse;
d.append(reverse);
d.append(" ");
}
System.out.println(d);
}
static void reverseWords(String s)
{
StringBuilder result=new StringBuilder();
Stack<Character> stack=new Stack<Character>();
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)!=' ')
{
stack.push(s.charAt(i));
}
else
{
while(!stack.isEmpty())
{
result.append(stack.pop());
}
result.append(" ");
}
}
while(!stack.isEmpty())
{
result.append(stack.pop());
}
System.out.println(result);
}
}