casillas
casillas

Reputation: 16793

Finding substring in the list

I am learning python by looking and also trying to solve interview questions.

In the following question and solution is provided.

Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

Example 1:

Input: "abab"

Output: True

Explanation: It's the substring "ab" twice.

Example 2:

Input: "aba"

Output: False

def repeatedSubstringPattern2(self, str):
        """
        :type str: str
        :rtype: bool
        """
        if not str:
            return False

        ss = (str + str)[1:-1]
        print ss
        return ss.find(str) != -1

My question is even though aba is listed as a False example, but looking at the solution it gives me a sense that it is true. Any idea?? What I am missing?

  ss = (aba +aba)[1:-1] --> abaaba[1:-1] --> baaba 
  baaba.find(aba) != -1 --> true??

Upvotes: 0

Views: 97

Answers (1)

wpercy
wpercy

Reputation: 10090

The logic you use in this line:

ss = (aba +aba)[1:-1] --> abaaba[1:-1] --> baaba 

is incorrect. When you slice a list, it doesn't include the element at the second slicing index. The correct logic would be:

ss = (aba +aba)[1:-1] --> abaaba[1:-1] --> baab

Upvotes: 2

Related Questions