Given a square grid of characters in the range ascii[a-z], rearrange elements of each row alphabetically, ascending. Determine if the columns are also in ascending alphabetical order, top to bottom. Return YES
if they are or NO
if they are not.
Example:
Input: grid = ["ebacd", "fghij", "olmkn", "trpqs", "xywuv"]
Output: YES
Approach
Java
import java.util.Arrays;public class GridChallenge {public static void main(String[] args) {String[] grid = { "ebacd", "fghij", "olmkn","trpqs", "xywuv" };System.out.println(gridChallenge(grid));}static String gridChallenge(String[] grid) {int n = grid.length;for (int i = 0; i < n; i++) {Arrays.sort(grid[i].toCharArray());}char arr[][] = new char[n][n];for (int i = 0; i < n; i++) {for (int j = 0; j < grid[i].length(); j++)arr[i][j] = grid[i].charAt(j);}int flag = 0;for (int j = 0; j < n; j++) {for (int i = 1; i < n; i++) {if (arr[i][j] < arr[i - 1][j]) {flag = 1;break;}}}if (flag == 0)return "YES";elsereturn "NO";}}
C++
#include <bits/stdc++.h>using namespace std;string gridChallenge(vector<string> grid){int n = grid.size();for (int i = 0; i < n; i++){sort(grid[i].begin(), grid[i].end());}char arr[n][n];for (int i = 0; i < n; i++){for (int j = 0; j < grid[i].size(); j++)arr[i][j] = grid[i][j];}int flag = 0;for (int j = 0; j < n; j++){for (int i = 1; i < n; i++){if (arr[i][j] < arr[i - 1][j]){flag = 1;break;}}}if (flag == 0)return "YES";elsereturn "NO";}int main(){vector<string> grid = {"ebacd", "fghij", "olmkn","trpqs", "xywuv"};cout << gridChallenge(grid);return 0;}
No comments:
Post a Comment