About Me

Friday, May 4, 2012

determine whether the given string is of form pZq where q is reverse of q. p and q can contain only X and Y.

like if p=XXYX then z will be XYXX
for ex XXYXXXYXX is valid

the constraints is that "you can read only the next character at each point" .

3 comments:

  1. I think in your question:
    "like if p=XXYX then z will be XYXX
    for ex XXYXXXYXX is valid"

    'z' should be replaced by 'q' and the Input should be:
    XXYXZXYXX

    Correct me, if I am wrong

    ReplyDelete
  2. For such problems we can use a DFA
    -Make new states of 'X' and 'Y' till the occurrence of 'Z' and store the same into a stack
    - After than pop an element from the stack and compare it with the next element
    - If at the end stack is empty, string is of format pZq, in case of mismatch it isn't

    ReplyDelete
  3. int indexOfZ = str.indexOf("Z");
    if(indexOfZ == -1)
    return false
    String revP = str.subString(0, indexOfZ).reverse();
    String q = str.subString(indexOfZ+1)

    if(revP.equals(q))
    {
    return true;
    }
    else
    return false;

    ReplyDelete

Hi thanks , we will get back to you shortly !!!