From Optimization Dynamics to Generalization Bounds via {\L}ojasiewicz Gradient Inequality