
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count K-Length Substring Occurring More Than Once in Python
Suppose we have a string s and a number k, we have to find the number of k-length substrings of s, that occur more than once in s.
So, if the input is like s = "xxxyyy", k = 2, then the output will be 2
To solve this, we will follow these steps −
- seen := a new list
- for i in range 0 to size of s - k, do
- t := substring of s [from index i to i + k - 1]
- insert t at the end of seen
- mp := a map for all distinct element in seen and their occurrences
- return sum of all occurrences of each element in mp where occurrence is more than 1
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s, k): from collections import Counter seen = [] for i in range(len(s) - k + 1): t = s[i : i + k] seen.append(t) s = Counter(seen) return sum(1 for x in s.values() if x > 1) ob = Solution() print(ob.solve("xxxyyy",2))
Input
"xxxyyy",2
Output
2
Advertisements