ihsan.a
BAN USERpublic class Main {
public static void main(String[] args) {
String words[] = {"Apple", "Melon", "Orange", "Watermelon"};
String parts[] = {"a", "mel", "lon", "el", "An"};
for(String word: words)
{
String newWord= findSubString(word, parts);
System.out.println(newWord);
}
}
static String findSubString(String word, String[] parts)
{
String maxPart = "";
int startIndex = 0;
for (String part: parts) {
boolean matchFound = false;
int wordIndex = 0;
for(int i=0; i<word.length(); i++)
{
char wordChar = word.charAt(i);
for(char partChar :part.toCharArray())
{
if(wordChar == partChar)
{
matchFound=true;
if(wordIndex+1 < word.length()) {
wordChar = word.charAt(++wordIndex);
}
}
else
{
matchFound=false;
break;
}
}
if(matchFound)
{
if(part.length() > maxPart.length())
{
maxPart = part;
startIndex = i;
}
break;
}
wordIndex++;
}
}
String newWord = word;
if(!maxPart.isEmpty()) {
newWord = word.substring(0,startIndex) + "[" + maxPart + "]" + word.substring(startIndex + maxPart.length());
}
return newWord;
}
}
- ihsan.a January 20, 2019