To elaborate on the explanation provided by @Alex, the reasoning is because when we look at the PDE we notice that the $S$ terms appear in pairs with the $\dfrac{\partial}{\partial S}$, i.e. $S\dfrac{\partial}{\partial S}$ and $S^2\dfrac{\partial^2}{\partial S^2}$. What this says it that if we were to try a polynomial function of $S$ then after applying these operators then the exponent of $S$ would not change, i.e. $S\dfrac{\partial S^n}{\partial S} \to nS^n$ and similarly $S^2\dfrac{\partial^2 S^n}{\partial S^2} \to n(n-1)S^n$. This means that after trying this ansatz in the PDE it would cancel leaving only a polynomial equation for $n$, which if we can show has solutions, justifies the initial ansatz.
The overall reasoning behind this is that trying to solve PDEs in general is tedious, so always look for shortcuts specific to the problem. A good mentality to solving a PDE problem is that solving the actual PDE in general is relatively easy, the relatively hard bit is applying the boundary conditions! Hence whenever solving a PDE we should keep in mind how are our boundary conditions expressed? If they are a polynomial function of $S$ then we should try a polynomial function as our ansatz. If we have a wave boundary condition then try a wave ansatz, etc.
e.g.
The following
$$
\dfrac{\sigma^2}{2} \frac{\partial^2 P}{\partial S^2}-rP+r\frac{\partial P}{\partial S}=0
$$
would typically motivate a solution $P = \exp(\mu S)$ and then we would solve for $\mu$.
A more general justification can be found in most courses in Linear Algebra and I would recommend seeing examples of the Sturm-Liouville problem. The general reasoning though is to change the basis into one that is easy to solve, e.g. we could solve your original PDE in terms of $\sin(S)$ and $\cos(S)$, or Legendre polynomials, Bessel functions, etc., but the solutions would not be anywhere as tidy. But you only learn which to try by drawing on experience, and even after years of experience and clever justifications it can frequently resort to trial and error.
I hope this helps.