Reputation:
Definition of NICE is as below
A word is nice if it contains the same string as a proper prefix as well as a proper suffix. A proper prefix or suffix cannot be a long as the word itself. For example:- manama is nice because it contains ma as a proper prefix as well as a proper suffix.So the output would be "NICE"
panama is not a nice word.Output in this case would be "NOT"
My solution working fine but it is taking too long for some of the test cases where length of input(word) is long.
public static String findNice(String word) {
if((word == null) || (word.length()==1))
return "NOT";
char[] charArr = word.toCharArray();
//System.out.println(charArr.length);
boolean flag = false;
for(int i = (charArr.length)/2; i < charArr.length ;++i) {
if(charArr[0] == charArr[i]) {
flag = compareSubString(charArr,0,i);
}
}
if(flag)
return "NICE";
return "NOT";
}
public static boolean compareSubString(char[] seq, int ptr1, int ptr2) {
boolean flag = true;
for(int i = ptr1,j = ptr2 ; j < seq.length ;++i,++j) {
if(seq[i] != seq[j]) {
flag = false;
}
}
return flag;
}
How to improve it further.
Upvotes: 0
Views: 148
Reputation: 16498
A shorter and readable option could be to use String.endswith
public static String findNice(String word) {
String result = "NOT";
for(int i = 0; i<word.length()/2;i++){
String prefix = word.substring(0, i+1);
if(word.endsWith(prefix)){
result = "NICE! Prefix = "+prefix;
}
}
return result;
}
Upvotes: 0
Reputation: 674
You can try this to avoid two for loop
public static String findNice(String word) {
int length = word.length();
int haftLength = length / 2;
for (int i = 0; i <= haftLength; i++) {
if(getFirstWordByIndex(word, i).equalsIgnoreCase(getLastWordByIndex(word, i, length))) {
return "NICE";
}
}
return "NOT";
}
public static String getFirstWordByIndex(String str, int index) {
return str.substring(0, index + 1);
}
public static String getLastWordByIndex(String str, int index, int length) {
return str.substring(length - index-1, length);
}
Upvotes: 0
Reputation: 544
Try adding break statement as below:-
if(seq[i] != seq[j]) {
flag = false;
break;
}
Upvotes: 2