Understanding Distance Calculation in Programming with 26 Letters
Have you ever thought about how far you would need to walk to visit 26 animals corresponding to A-Z, lined up in a straight line (with a distance of 1 meter between each)? This is not just a simple math problem, but a classic example of “position mapping + cumulative calculation” in programming!
The “Hidden Logic” in the Problem
The 26 animals’ homes correspond to the string<span>S</span> (for example, input<span>ABCDEFGHIJKLMNOPQRSTUVWXYZ</span>), starting at home A, and visiting in the order A→B→C→…→Z, we need to calculate the total distance traveled.
For example:
- If the input is a continuous A-Z, starting from A (position 0) to B (1) is 1 meter, from B to C (2) is 1 meter… The total distance is 25 meters (which is exactly the output of example 1).
How Does Programming “Calculate Distance”?
The core consists of two steps:record position, calculate difference.
- “Positioning” each letter: Use an array
<span>pos</span>to store the positions of A-Z — for example, if the 5th character in the string is<span>F</span>, then<span>pos[5]</span><code><span> corresponds to the position of F.</span> - Cumulatively add each segment of movement distance: Starting from the position of A, calculate the absolute difference to the positions of B, C…Z, and summing them gives the total distance.
The “Clever Idea” in the Code

This piece of code is only about 20 lines long, yet it clearly explains the logic of “mapping + accumulation” — even if the order of the animals’ homes is scrambled (for example, in sample 2 <span><span>VENFLQURTCHXAOMGJYIZDKBSHP</span></span>), it can still quickly calculate the total distance of 231 meters.
What Does This Problem Teach Us?
This is actually a simplified version of “hash mapping【<span>pos</span> array】 + greedy traversal” in programming:
- Using an array as a “dictionary” to achieve quick lookup of letters to positions;
- The “greedy” approach of traversing in order ensures that each step is the shortest path at that moment.
There are many similar scenarios in life: for example, a delivery person delivering food in the order of orders, calculating the total distance; or you shopping in a supermarket according to a list, calculating the distance walked past the shelves — essentially all follow the logic of “positioning + accumulation”.
Basic Knowledge Points: 【Hash Mapping, Greedy Algorithm】
