-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathStringChain.java
75 lines (65 loc) · 1.49 KB
/
StringChain.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
/**
*
*/
package com.javaaid.ip.cleartrip;
import java.util.Scanner;
/**
* @author Kanahaiya Gupta
*
*/
public class StringChain {
static int charCount = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
/*int N = sc.nextInt();
String words[] = new String[N];
for (int i = 0; i < N; i++) {
words[i] = sc.next();
}*/
String[] words = new String[]{"a", "b","ba", "bca", "bda", "bdca"};
int result = calulateLongestChain(words);
System.out.println(result);
sc.close();
}
/**
* @param words
* @return
*/
private static int calulateLongestChain(String[] words) {
int maxLongestChainOfCharacter = 0;
for (String word : words) {
int currentCharCount= findMaxChain(words, word, 0);
maxLongestChainOfCharacter = Math.max(maxLongestChainOfCharacter, currentCharCount);
}
return maxLongestChainOfCharacter;
}
/**
* @param word
* @return
*/
private static int findMaxChain(String[] words, String word, int lenCounter) {
if (!wordsContains(words, word)) {
return 0;
}
lenCounter++;
charCount = lenCounter;
for (int i = 0; i < word.length(); i++) {
StringBuilder sb = new StringBuilder(word);
sb.delete(i, i + 1);
findMaxChain(words, sb.toString(), lenCounter);
}
return charCount;
}
/**
* @param string
* @return
*/
private static boolean wordsContains(String[] words, String string) {
for (String word : words) {
if (word.equals(string)) {
return true;
}
}
return false;
}
}