File tree 1 file changed +49
-0
lines changed
Course 1 - Introduction to JAVA/Test-2
1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Given a string S (that can contain multiple words), you need to find the word which has minimum length.
3
+ Note : If multiple words are of same length, then answer will be first minimum length word in the string.
4
+ Words are seperated by single space only.
5
+
6
+ Input Format :
7
+ String S
8
+
9
+ Output Format :
10
+ Minimum length word
11
+
12
+ Constraints :
13
+ 1 <= Length of String S <= 10^5
14
+
15
+ Sample Input 1 :
16
+ this is test string
17
+ Sample Output 1 :
18
+ is
19
+
20
+ Sample Input 2 :
21
+ abc de ghihjk a uvw h j
22
+ Sample Output 2 :
23
+ a
24
+ */
25
+
26
+
27
+ public class MinLengthWord {
28
+
29
+ public static String minLengthWord (String input ){
30
+
31
+ // Write your code here
32
+ String minWord ="" ;
33
+ int prevSpace =0 ;
34
+ input = " " + input + " " ;
35
+ for (int i =1 ;i <input .length ();i ++)
36
+ {
37
+ if (input .charAt (i ) == ' ' )
38
+ {
39
+ String word = input .substring (prevSpace +1 ,i );
40
+ if (word .length () < minWord .length () || minWord .length () == 0 )
41
+ {
42
+ minWord =word ;
43
+ }
44
+ prevSpace =i ;
45
+ }
46
+ }
47
+ return minWord ;
48
+ }
49
+ }
You can’t perform that action at this time.
0 commit comments