-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongestSubstring.java
99 lines (85 loc) · 2.04 KB
/
LongestSubstring.java
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package sample.ankit.amazon;
import java.util.Arrays;
import java.util.List;
public class LongestSubstring {
public static void main(String[] args) {
// TODO Auto-generated method stub
//List<String> words=Arrays.asList("bc","ab","bde","ae","ae");
//String input="abcde";
List<String> words=Arrays.asList("be");
String input="abcde";
System.out.println(findLongestSequence(words, input));
}
public static String findLongestSequence(List<String> words,String input){
int sizeOfSequence=0;
String finalWord="";
for(String aWord:words){
if(isASubSequence(aWord, input)){
int sizeOfCurrentWord=aWord.length();
if(sizeOfCurrentWord>sizeOfSequence){
sizeOfSequence=sizeOfCurrentWord;
finalWord=aWord;
}
}
}
return finalWord;
}
//least optimal = > for each word we have to scan the input word again
private static boolean isSubSequence(String word,String input){
int indexOfLast=-1;
char[] allChars=word.toCharArray();
for(char aChar:allChars){
int index=input.indexOf(aChar);
if(index==-1){
return false;
}else{
if(index<=indexOfLast){
return false;
}
indexOfLast=index;
}
}
return true;
}
private static boolean isASubSequence(String word,String input){
char[] inputChars=input.toCharArray();
char[] wordChars=word.toCharArray();
boolean result=true;
boolean found=false;
int i=0,j=0;
while(i < wordChars.length){
found=false;
while(j< inputChars.length){
if(wordChars[i] == inputChars[j]){
i++;
j++;
found=true;
break;
}else{
j++;
}
}
if(found==false){
result=false;
break;
}
}
return result;
}
private static boolean isASubSequenceSingleLoop(String word,String input){
char[] inputChars=input.toCharArray();
char[] wordChars=word.toCharArray();
for(int i=0,j=0;i<wordChars.length && j<inputChars.length; ){
if(wordChars[i] == inputChars[j]){
if(i==wordChars.length-1){
return true;
}
i++;
j++;
}else{
j++;
}
}
return false;
}
}