r123454321
r123454321

Reputation: 3403

Sorting the letters in a string by the order they occur?

Is sorting the letters in a string by the order they occur doable in linear time?

For instance, boyhood would sort to boooyhd.

Upvotes: 0

Views: 226

Answers (1)

Spade
Spade

Reputation: 2280

Yes, here is an O(2n) solution in python:

import sys

word = raw_input("Enter string to sort:")
wordDict = {}

for letter in word:
    if letter in wordDict:
        wordDict[letter] = wordDict[letter] + 1
    else:
        wordDict[letter] = 1

for letter in word:
    sys.stdout.write(letter*wordDict[letter])
    wordDict[letter] = 0

Upvotes: 1

Related Questions