python - Generating palindromic anagrams of a string of length upto 10^5 -
i have tried next takes much time when seek string of 17 characters.
string = input() def permute(xs, low=0): if low + 1 >= len(xs): yield xs else: p in permute(xs, low + 1): yield p in range(low + 1, len(xs)): xs[low], xs[i] = xs[i], xs[low] p in permute(xs, low + 1): yield p xs[low], xs[i] = xs[i], xs[low] p in permute(list(string)): mstr = "".join(p) if mstr == mstr[::-1]: print("yes") break
this solution 'game of thrones' challenge on hackerrank. how can cut down execution time , create run real fast strings of length 10^5?
thanks.
trying combination cannot fast enough, of course. there much simpler way it. based on next observation: let's assume count[c]
number of occurrences of c
in given string. reply yes if , if number of characters odd value of count
less or equal 1. observation gives simple o(n)
solution.
here pseudo code:
count[c] = 0 each character c appears in string = 1...length(s): count[s[i]] += 1 with_odd_count = 0 each c: if count[c] % 2 == 1: with_odd_count += 1 if with_odd_count <= 1: print("yes") else: print("no")
python chr ord
No comments:
Post a Comment