Problem:
Given a string, if a length 2 substring appears at both its beginning and end, return a string without the substring at the beginning, so "HelloHe" yields "lloHe". The substring may overlap with itself, so "Hi" yields "". Otherwise, return the original string unchanged.
without2("HelloHe") → "lloHe"
without2("HelloHi") → "HelloHi"
without2("Hi") → ""
Solution:
public String without2(String str) { int len = str.length(); if (len == 2) return ""; if (len < 2) return str; else { if (str.substring(0,2).equals(str.substring(len-2, len))) return str.substring(2,len); else return str; } }
public String without2(String str) {
ReplyDeleteif(str.length()>1 && str.substring(0,2).equals(str.substring(str.length()-2)))
return str.substring(2,str.length());
else return str;
}
this one actually worked for me, the suggested solution in the main post didn't :) thanks!
Deletepublic String without2(String str) {
ReplyDeleteint x = str.length();
if(x == 1)
{
return str;
}
else if(x <= 2)
{
return "";
}
else if(str.substring(0,2).equals(str.substring(x-2,x)))
{
return str.substring(2,x);
}
else
{
return str;
}
}
public String without2(String str) {
ReplyDeleteif(str.length() >= 2) {
String front = str.substring(0, 2), back = str.substring(str.length() - 2);
if(front.equals(back)) return str.substring(2);
}
return str;
}
public String without2(String str) {
ReplyDeletereturn str.length() > 1 && str.substring(0,2).equals(str.substring(str.length()-2)) ? str.substring(2, str.length()):str;
}
public String without2(String str) {
ReplyDeleteif(str.length()>3){
String a=str.substring(0,2);
String b=str.substring(str.length()-2,str.length());
String c=str.substring(2,str.length()-2);
if(a.equals(b)){
return c+a;
}
}if(str.length()==2){
return "";
}
if(str.length()==3 && ((str.substring(0,1)).equals(str.substring(str.length()-1,str.length())))){
return (str.substring(1,str.length()-1));
}
else return str;
}
public String without2(String str) {
ReplyDeleteif(str.length()>1 && str.substring(0,2).equals(str.substring(str.length()-2)))
return str.substring(2);
else return str;
}
public String without2(String str)
ReplyDelete{
int len = 2;
if(str.length()<2)
len = str.length();
String data = str;
if(str.endsWith(str.substring(0,len)) && str.length() > 1)
data = str.substring(len);
return data;
}
public String without2(String str) {
ReplyDeleteint len = str.length();
if (len == 2)
{
return "";
}
else if (len <= 1)
{
return str;
}
else if ( str.substring(0,2).equals( str.substring(len-2, len) ) )
{
return str.substring( 2,len );
}
return str;
}
Removed the extra bracket.