|
| 1 | +# Number of Good Ways to Split a String |
| 2 | +# https://leetcode.com/problems/number-of-good-ways-to-split-a-string/ |
| 3 | + |
| 4 | +class Solution(object): |
| 5 | + def __init__(self): |
| 6 | + # key = (start index, end index) value = distinct character count |
| 7 | + self.tuplesOfDistinctChars = {} |
| 8 | + |
| 9 | + def addToDistinctAndCharCountHashSets(self, distinct, charCount, letter): |
| 10 | + # if we have not seen it |
| 11 | + if (letter not in charCount): |
| 12 | + charCount[letter] = 1 |
| 13 | + distinct[letter] = True |
| 14 | + print "The character",letter,"is distinct and the distinct char count is",len(distinct) |
| 15 | + else: |
| 16 | + charCount[letter] = charCount[letter]+1 |
| 17 | + print "The character",letter,"is not distinct and the distinct char count is",len(distinct) |
| 18 | + |
| 19 | + def distinctLeft(self, s): |
| 20 | + # count distinct from left to right |
| 21 | + # key = char, value = Number of times seen |
| 22 | + charCount = {} |
| 23 | + # key = char, value = True |
| 24 | + distinct = {} |
| 25 | + for i in range(len(s)): |
| 26 | + #print "For 0 to ",i,s[0:i+1] |
| 27 | + self.addToDistinctAndCharCountHashSets(distinct, charCount, s[i]) |
| 28 | + self.tuplesOfDistinctChars[(0, i)] = len(distinct) |
| 29 | + |
| 30 | + def distinctRight(self, s): |
| 31 | + # count distinct from right to left |
| 32 | + # key = char, value = Number of times seen |
| 33 | + charCount = {} |
| 34 | + # key = char, value = True |
| 35 | + distinct = {} |
| 36 | + for i in range(len(s)-1, -1, -1): |
| 37 | + #print "For",len(s)-1,"to",i,"string",s[i:len(s)] |
| 38 | + self.addToDistinctAndCharCountHashSets(distinct, charCount, s[i]) |
| 39 | + self.tuplesOfDistinctChars[(i, len(s)-1)] = len(distinct) |
| 40 | + |
| 41 | + |
| 42 | + def numSplits(self, s): |
| 43 | + self.distinctLeft(s) |
| 44 | + self.distinctRight(s) |
| 45 | + # split the string at various intervals and count good splits |
| 46 | + goodSplitCount = 0 |
| 47 | + for i in range(len(s)-1): |
| 48 | + print "First half", s[0:i+1],"Second half",s[i+1:len(s)] |
| 49 | + print "0 to",i,"and",i+1,"to",len(s)-1 |
| 50 | + print "distinct in first half",self.tuplesOfDistinctChars[(0, i)] |
| 51 | + print "distinct in seconf half", self.tuplesOfDistinctChars[(i+1, len(s)-1)] |
| 52 | + if (self.tuplesOfDistinctChars[(0, i)] == self.tuplesOfDistinctChars[(i+1, len(s)-1)]): |
| 53 | + goodSplitCount = goodSplitCount + 1 |
| 54 | + print "*"*25 |
| 55 | + return goodSplitCount |
| 56 | + """ |
| 57 | + :type s: str |
| 58 | + :rtype: int |
| 59 | + """ |
| 60 | + |
0 commit comments