3

I'm trying to solve this CodingBat problem:

Return true if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not.

xyzThere("abcxyz") → true
xyzThere("abc.xyz") → false
xyzThere("xyz.abc") → true

My attempt:

public boolean xyzThere(String str) {
  boolean res = false;

  if(str.contains(".xyz") == false && str.contains("xyz")){
    res = true;
  }

  return res;

}

The problem is that is passes all the tests except the one below because it contains two instances of xyz:

xyzThere("abc.xyzxyz")

How can I make it pass all tests?

Anders
  • 8,307
  • 9
  • 56
  • 88
Manas Bajaj
  • 1,133
  • 3
  • 16
  • 26
  • 1
    Why are you using a `for` loop and completely ignoring `i`? You're just going the same thing over and over, for every character in the string. And what _should_ `xyzThere("abc.xyzxyz")` return? – Matt Ball Apr 08 '13 at 19:53
  • what should be the result for the test case which you mentioned? Does it pass or not? – nommyravian Apr 08 '13 at 19:55
  • Depending on your philosophical bent, answer to `xyzThere("abc.xyzxyz")` may be `true` or `false` unless the question states if only the first occurrence of `xyz`/'.xyz' to check. Also, instead of `str.contains(".xyz") == false`, use `!str.contains(".xyz")`. And, drop the `for` loop. – Karan Goel Apr 08 '13 at 19:55
  • My bad, was trying to do it some other way, forgot to delete that line. – Manas Bajaj Apr 08 '13 at 19:56
  • @nommyravian, it should return 'true', but returns false in my case. – Manas Bajaj Apr 08 '13 at 19:57

20 Answers20

4
public static boolean xyzThere(String str) {
    int i = -1;
    while ((i = str.indexOf("xyz", i + 1 )) != -1) {
        if (i == 0 || (str.charAt(i-1) != '.')) {
            return true;
        }
    }
    return false;
}
Xavier Delamotte
  • 3,519
  • 19
  • 30
3

Alternatively, you could replace all occurrences of ".xyz" in the string with "", then use the .contains method to verify that the modified string still contains "xyz". Like so:

return str.replace(".xyz", "").contains("xyz");
R. Pehrson
  • 31
  • 3
2
public boolean xyzThere(String str) {
    return(!str.contains(".xyz") && str.contains("xyz"));
}

Edit: Given that ".xyzxyz" should return true, the solution should be:

public boolean xyzThere(String str) {
    int index = str.indexOf(".xyz");
    if(index >= 0) {
        return xyzThere(str.substring(0, index)) || xyzThere(str.substring(index + 4));
    } else return (str.contains("xyz"));
}
Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69
  • No, the thing is that your code returns the same output as mine, i.e. returning false for xyzThere("abc.xyzxyz"), however, it should return true. – Manas Bajaj Apr 08 '13 at 20:04
  • Ah, gotcha. I'll edit my answer accordingly. The new answer will strip off all instances of ".xyz" and will then return true of the string still contains an "xyz" – Zim-Zam O'Pootertoot Apr 08 '13 at 20:05
  • Try again, I've changed "str.substring(index)" to "str.substring(index + 4)" which should eliminate the stack overflows – Zim-Zam O'Pootertoot Apr 08 '13 at 20:12
2

The below code worked fine for me:

if '.xyz' in str:
  return xyz_there(str.replace('.xyz',''))
elif 'xyz' in str:
  return True

return False
Neel
  • 43
  • 5
  • 1
    Welcome to Stack Overflow. Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please [edit] your question and explain how it answers the specific question being asked. See [answer]. This is particularly important when answering old questions (this one is over eight years old) with existing answers. – ChrisGPT was on strike Aug 29 '21 at 23:21
1

Ok, I know everyone is eager to share their expertise but straight giving the kid the answer does little good.

@EnTHuSiAsTx94

I was able to pass all of the tests with three statements. Here is a hint: Try using the string replace method. Here is the method signature:

String replace(CharSequence target, CharSequence replacement)

On a minor note, the first condition in your if statement can be simplified from:

str.contains(".xyz") == false

to:

!str.contains(".xyz")

The contains method already returns true or false, so there is no need for the explicit equals comparison.

DXDenton
  • 11
  • 1
1
public boolean xyzThere(String str) {
return str.startsWith("xyz") || str.matches(".*[^.]xyz.*");
}
1

You can use the equivalent java code for the following solution:

def xyz_there(str):
  pres = str.count('xyz')
  abs = str.count('.xyz')
  if pres>abs:
    return True
  else:
    return False
Chris32
  • 4,716
  • 2
  • 18
  • 30
0

Ok, let's translate your question into a regexp:

^ From the start of the string
(|.*[^\.]) followed by either nothing or any amount of any chars and and any char except .
xyz and then xyz

Java code:

public static boolean xyzThere(String str) {
    return str.matches("^(|.*[^\\.])xyz");
}
Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73
0
boolean flag = false;
if(str.length()<=3){
   flag = str.contains("xyz"); 
}

for (int i = 0; i < str.length()-3; i++) {
    if (!str.substring(i, i+3).equals("xyz") && 
            str.substring(i, i+4).equals(".xyz")) {
        flag=false;
    }else{
        if(str.contains("xyz")) flag=true;
    }
}
return flag;
Emil Sierżęga
  • 1,785
  • 2
  • 31
  • 38
Pradeep
  • 1
  • 1
  • 4
0
public boolean xyzThere(String str) {
  boolean res=false;
  if(str.length()<3)res=false;
  if(str.length()==3){
    if(str.equals("xyz"))res=true;
    else res=false;
  }
  if(str.length()>3){
   for(int i=0;i<str.length()-2;i++){
     if(str.charAt(i)=='x' && str.charAt(i+1)=='y' && str.charAt(i+2)=='z'){
       if(i==0 || str.charAt(i-1)!='.')res=true;
     }
   }
  }
  return res;
}
coder kemp
  • 361
  • 2
  • 13
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/18376696) – Mamun Dec 29 '17 at 02:08
  • Well this does run all the test cases. Do test it before commenting and ignorantly down-voting. – coder kemp Dec 29 '17 at 18:49
0
public class XyzThereDemo {
    public static void main(String[] args) {
        System.out.println(xyzThere("abcxyz"));
        System.out.println(xyzThere("abc.xyz"));
        System.out.println(xyzThere("xyz.abc"));
    }

    public static boolean xyzThere(String str) {
        int xyz = 0;
        for (int i = 0; i < str.length() - 2; i++) {


            if (str.charAt(i) == '.') {
                i++;
                continue;

            }

            String sub = str.substring(i, i + 3);


            if (sub.equals("xyz")) {
                xyz++;
            }


        }

        return xyz != 0;
    }
}
tkuzub
  • 11
  • 1
0

Another method

public boolean xyzThere(String str) {
 if(str.startsWith("xyz")) return true;
for(int i=0;i<str.length()-3;i++) {
   if(str.substring(i+1,i+4).equals("xyz") && str.charAt(i)!='.') return true;
}
  return false;
}
Rares
  • 1
  • 2
0
public boolean xyzThere(String str) {

    if (str.startsWith("xyz")){
      return true;
    }

    for (int i = 0; i < str.length()-2; i++) {

        if (str.subSequence(i, i + 3).equals("xyz") && !(str.charAt(i-1) == '.')) {
            return true;
        }
    }
    return false;
}
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
0

This is the best possible and easiest way to solve this question with very simple logic:

def xyz_there(str):
  for i in range(len(str)):
    if str[i-1]!= '.' and str[i:i+3]=='xyz' :
      return True
  return False
0
 public boolean xyzThere(String str) {

    boolean flag = false;
    
    if (str.startsWith("xyz"))
    {
        return true;
    }

    for (int i = 0; i < str.length() - 3; i++)
    {
                                         
        if (str.charAt(i) != '.' && str.charAt(i + 1) == 'x'
            && str.charAt(i + 2) == 'y' && str.charAt(i + 3) == 'z')
        {
          flag = true;
          break;
        }
    }
    return  flag;
}
Ammy
  • 369
  • 2
  • 8
0
def xyz_there(str1):
  
  for i in range(len(str1)):
    if str1[i-1] != '.' and str1[i:i+3] == 'xyz':
      return True
  else:
    return False
0

def xyz_there(str):

if '.xxyz' in str:

return'.xxyz' in str

if '.' in str:

a=str.replace(".xyz","")

return 'xyz' in a

if '.' not in str:

return 'xyz' in str
-1

'''python

def xyz_there(str):

    dot=str.find('.')    # if period is present in str if not dot==-1
    if dot==-1:            # if yes dot will show position of period  
        return 'xyz' in str
    elif dot!=-1:                 #if period is present at position dot
        if 'xyz' in str[:dot]:    
            return True                    
        while str[dot+1:].find('.')!=-1:   #while another period is present 
            if  '.xyz' in str[dot+1:]==False:  # .xyz will not be counted  
                return True
        else:
            dot=dot+str[dot+1:].find('.')+2 #now dot=previous dot+new dot+2
    else:
        return 'xyz' in str[dot+2:]

'''

SANROOKIE
  • 35
  • 9
-1
def xyz_there(str):
  list = [i for i in range(len(str)) if str.startswith('xyz', i)]
  if list == []:
    return False
  else:
    found = 0
    for l in list:
      if str[l-1:l+3] != ".xyz":
        found += 1
    if found >=1:
      return True
    else:
      return False

Zoe
  • 27,060
  • 21
  • 118
  • 148
-2

simple solution just by replace and check the "xyz " in a thats it

def xyz_there(str):
   a=str.replace('.xyz','')
   return 'xyz' in a