LeetCode-in-Java

3931. Check Adjacent Digit Differences

Easy

You are given a string s consisting of digits.

Return true if the absolute difference between every pair of adjacent digits is at most 2, otherwise return false.

The absolute difference between a and b is defined as abs(a - b).

Example 1:

Input: s = “132”

Output: true

Explanation:

Example 2:

Input: s = “129”

Output: false

Explanation:

Constraints:

Solution

public class Solution {
    public boolean isAdjacentDiffAtMostTwo(String s) {
        for (int i = 0; i < s.length() - 1; i++) {
            if (Math.abs(s.charAt(i) - s.charAt(i + 1)) > 2) {
                return false;
            }
        }
        return true;
    }
}