请求二维字符数组中连续相同字符最长长度的算法或伪代码
Alright, let's walk through how to solve this grid problem where we need to find the longest run of identical consecutive characters (either horizontal or vertical). Below is a straightforward algorithm and pseudocode that's easy to translate into C:
整体算法思路
The core idea is to check every possible horizontal and vertical sequence in the grid, keeping track of the longest consecutive streak we find:
- Start with a maximum count of 1 (since even a single character counts as a streak of 1)
- Horizontal check: Iterate through each row, comparing each character to the one before it. Count consecutive matches and update the maximum streak whenever we find a longer one.
- Vertical check: Do the same for each column, comparing each character to the one above it. Again, update the maximum streak as needed.
- After checking all rows and columns, the maximum count will be our answer.
伪代码实现
// Read number of test cases READ T FOR each test case in 1..T: // Read grid dimensions: n rows, m columns READ n, m // Initialize and populate the grid CREATE 2D array grid[n][m] FOR i from 0 to n-1: READ row (a string of m lowercase characters) FOR j from 0 to m-1: grid[i][j] = row[j] // Set initial maximum streak to 1 (minimum possible value) max_streak = 1 // Check horizontal consecutive characters FOR each row i in 0..n-1: current_streak = 1 FOR each column j in 1..m-1: IF grid[i][j] == grid[i][j-1]: current_streak += 1 // Update max if current streak is longer IF current_streak > max_streak: max_streak = current_streak ELSE: // Reset streak when characters don't match current_streak = 1 // Check vertical consecutive characters FOR each column j in 0..m-1: current_streak = 1 FOR each row i in 1..n-1: IF grid[i][j] == grid[i-1][j]: current_streak += 1 IF current_streak > max_streak: max_streak = current_streak ELSE: current_streak = 1 // Output the result for this test case PRINT max_streak
Key Notes
- We initialize
max_streakto 1 to handle edge cases where all characters in the grid are unique (so the longest streak is 1). - Separating horizontal and vertical checks keeps the logic simple and easy to debug.
- We update
max_streakimmediately whenever we find a longer streak to ensure we never miss the maximum value.
内容的提问来源于stack exchange,提问作者harish
相关产品推荐
相关产品推荐

