This paper focuses on matching 1D structures by variational methods. We provide rigorous rules for the construction of the cost function, on the basis of an analysis of properties which should be satisfied by the optimal matching. A new, exact, dynamic programming algorithm is then designed for the minimization. We conclude with experimental results on shape comparison.