rishu110067

Untitled

Feb 19th, 2022 (edited)
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.96 KB | None | 0 0
  1. /*
  2. Whether a list of strings is sorted given a specific alphabet
  3. Time complexity: O(N * M) where N = no. of words and M = size of each word
  4. */  
  5.  
  6. using System;
  7.  
  8. public class Solution {
  9.     static public void Main () {
  10.         char[] alphabet = new char[] {'c', 'b', 'a', 't'};
  11.         string[] words = new string[] {"cat", "bat", "tab"};
  12.        
  13.         int[] order = new int[26];
  14.         for(int i = 0; i < alphabet.Length; i++) {
  15.             order[alphabet[i] - 'a'] = i;
  16.         }
  17.    
  18.         bool sorted = true;
  19.         for(int i = 1; i < words.Length; i++) {
  20.             bool greater = true;
  21.             for(int j = 0; j < words[i-1].Length; j++) {
  22.                 if(j >= words[i].Length || order[words[i][j] - 'a'] < order[words[i-1][j] - 'a']) {
  23.                     greater = false;
  24.                 }
  25.                 else if(order[words[i][j] - 'a'] > order[words[i-1][j] - 'a']) {
  26.                     break;
  27.                 }
  28.             }
  29.            
  30.             if(!greater) {
  31.                 sorted = false;
  32.                 break;
  33.             }
  34.         }
  35.         Console.Write(sorted);
  36.     }
  37. }
Add Comment
Please, Sign In to add comment