Home > Software design >  Find a String Hackerrank
Find a String Hackerrank

Time:03-18

Input:ABCDCDC CDC Output:2

def count_substring(string, sub_string):
        for i in range(0,len(string)):
            ans=string.count(sub_string)
            return ans

I am getting 1 as output how can I get 2 as output and read the full string

CodePudding user response:

My solution was: for each character, check if the string from that specific character begins with the sub string required, so that overlapping ones are accounted for too

def count_substring(string, sub_string):
  total = 0
  for i in range(len(string)):
      if string[i:].startswith(sub_string):
          total  = 1
  return total

CodePudding user response:

From every index look forward for next n characters if they match, n being the size of substring

def count_substring(string, sub_string):
    n = len(sub_string)
    ans = 0
    for i in range(0,len(string)):
        if(i n > len(string)):#out of range problem
            break
        ans =string.count(sub_string,i,i n)
    return ans

CodePudding user response:

def count_substring(string, sub_string):
  return {s: string.count(s) for s in set(string)}

OUTPUT:

{' ': 1, 'B': 1, 'A': 1, 'D': 3, 'C': 5}
  • Related