forked from Itachi-Ucchiha/BasicDSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7thJune(II).java
More file actions
73 lines (48 loc) · 1.42 KB
/
Copy path7thJune(II).java
File metadata and controls
73 lines (48 loc) · 1.42 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
63
64
65
66
67
68
69
70
71
72
73
public class reverseWordsinString {
static String reverse(String s){
s = s.trim().replaceAll(" +", " ");
String[] arr = s.split(" ");
int i =0;
int j =arr.length-1;
while(i<j){
String temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;
}
String res = "";
for(int x = 0; x<arr.length-1; x++){
res+=arr[x]+" ";
}
return res+arr[arr.length-1];
// for(String x : arr){
// System.out.print(x+" ");
// }
}
static String reverse2(String s){
String wordarr[] = s.split(" ");
String sentence = "";
int n = wordarr.length;
for(int i = n-1; i>=0; i--){
if(wordarr[i].equals("")){
continue;
}
sentence += wordarr[i];
}
sentence = sentence.trim();
return sentence;
}
// by collections
// list is the parent of the collection
static String appraoch3(String s){
s=s.trim();
List<String> wordsList = Arrays.asList(s.split("\\s+"));
Collections.reverse(wordsList);
return String.join(" ", wordsList);
}
public static void main(String[] args) {
String s = " hello world ";
System.out.println(reverse(s));
}
}