forked from markandey007/hacktoberfest_2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest common prefix leetcode
67 lines (59 loc) · 1.33 KB
/
longest common prefix leetcode
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
import java.util.*;
public class longestcommonprefix
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=3;
String s[]=new String[n];
for(int i=0;i<n;i++)
{
s[i]=sc.nextLine();
}
sort(s,n);
String w=s[0];
String s2="";
String m="";
for(int i=0;i<w.length();i++)
{
char ch=w.charAt(i);
s2=s2+ch;
for(int j=1;j<n;j++)
{
int len=s2.length();
String s3=s[i].substring(0,len);
if(s2.equalsIgnoreCase(s3))
{
m=s2;
}
else
{
if(m=="")
{
System.out.println(-1);
}
else{
System.out.println(m);
}
break;
}
s3="";
}
}
s2="";
}
static void sort(String []s, int n)
{
for (int i=1 ;i<n; i++)
{
String temp = s[i];
int j = i - 1;
while (j >= 0 && temp.length() < s[j].length())
{
s[j+1] = s[j];
j--;
}
s[j+1] = temp;
}
}
}