Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Whether a list of strings is sorted given a specific alphabet
- Time complexity: O(N * M) where N = no. of words and M = size of each word
- */
- using System;
- public class Solution {
- static public void Main () {
- char[] alphabet = new char[] {'c', 'b', 'a', 't'};
- string[] words = new string[] {"cat", "bat", "tab"};
- int[] order = new int[26];
- for(int i = 0; i < alphabet.Length; i++) {
- order[alphabet[i] - 'a'] = i;
- }
- bool sorted = true;
- for(int i = 1; i < words.Length; i++) {
- bool greater = true;
- for(int j = 0; j < words[i-1].Length; j++) {
- if(j >= words[i].Length || order[words[i][j] - 'a'] < order[words[i-1][j] - 'a']) {
- greater = false;
- }
- else if(order[words[i][j] - 'a'] > order[words[i-1][j] - 'a']) {
- break;
- }
- }
- if(!greater) {
- sorted = false;
- break;
- }
- }
- Console.Write(sorted);
- }
- }
Add Comment
Please, Sign In to add comment