File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Given a sequence of words written in the alien language, and the
3
+ order of the alphabet, return true if and only if the given words
4
+ are sorted lexicographically in this alien language.
5
+
6
+ Space: O(1)
7
+ Time: O(n*m)
8
+ (Where n is the number of words and m the average length of the elements in words)
9
+ */
10
+
11
+
12
+ bool isAlienSorted (char * * words , int wordsSize , char * order ){
13
+ int alphabet [26 ] = {0 };
14
+ for (int i = 0 ; i < 26 ; i ++ )
15
+ alphabet [order [i ] - 'a' ] = i ;
16
+ for (int i = 1 ; i < wordsSize ; i ++ ) { // We compare words[i-1] and words[i]
17
+ int j = 0 ;
18
+ while (words [i - 1 ][j ]!= '\0' && words [i ][j ]!= '\0' ) { // Iterates through all letters of words
19
+ int v_i_1 = alphabet [words [i - 1 ][j ] - 'a' ];
20
+ int v_i = alphabet [words [i ][j ] - 'a' ];
21
+ if (v_i_1 != v_i ) {
22
+ if (v_i_1 > v_i ){
23
+ return false;
24
+ }
25
+ break ;
26
+ }
27
+ j ++ ;
28
+ }
29
+ if (words [i - 1 ][j ]!= '\0' && words [i ][j ] == '\0' ){ // If words[i] is shorter than words[i-1]
30
+ return false;
31
+ }
32
+ }
33
+ return true;
34
+ }
You can’t perform that action at this time.
0 commit comments