Skip to content

Commit 1486893

Browse files
authored
Create MinLengthWord.java
1 parent aa5eb11 commit 1486893

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
}

0 commit comments

Comments
 (0)