This is not an easy problem.
Simple methods based on "knowing the key signature" only work for simple music. Even in straightforward common-practice harmony, secondary dominants and chromatic passing notes can quickly introduce more than 12 functionally correct spellings of the 12 notes in the chromatic scale within a single piece of music in a major key. For pieces in minor keys the problem is greater, since there is usually a greater diversity of major and minor chords with the same root note.
Simple methods don't work when confronted with music as harmonically straightforward as for example Mendelssohn's well known "Wedding march" - where the second chord of a piece in C major is actually B7 (i.e. B dominant seventh, not B diminished)
As a example of the ambiguities that have to be resolved, the note spellings F - A flat - B or F - A flat - C flat are both "correct" in C minor, in different situations. One is functionally a (partial) dominant chord with root G, the other is functionally part of a Bb chord with a flat 9th, which could be a secondary dominant of Eb.
A good source of evidence that this is a hard problem is the fact that many commercial notation programs make a complete mess of it, requiring much hand editing to fix the mistakes - or publishing a score which makes it obvious that its author doesn't understand music notation. The following example was recently put in front of a professional rehearsal pianist, playing for auditions for a music theatre production in the capital of a first-world country...
Within two bars of supposedly F major, we have a C chord spelled with B sharp instead of C, followed by an so-called A sharp major chord (but with D natural instead of C double sharp) instead of B flat! And that isn't an isolated mistake - the whole score is similar nonsense.
One of the best algorithms for doing this right is the so-called "CS13" by David Meredith. It works by identifying both the "local key" (which is not necessarily the same as the key signature) and the voice leading of adjacent notes. A full description and examples (50 pages long) is here.