What is Subsequence? A subsequence of is a sequence defined by , where is an increasing sequence of indices . For example, the prime ...
A subsequence of is a sequence
defined by
, where
is an increasing sequence of indices .
For example, the prime numbers are a subsequence of the positive integers.
ASCII of 'a' is 97, 'b' is 98, 'c' is 98 and so on. If the string is 'abc' then it is subsequence because a<b<c. Similarly if string is 'azb' then it is not subsequence because a<z>b.
Implementation
Method 1
function alphabetSubsequence(str) {
// write code here.
flag = 0;
for(let i=0; i<str.length-1;i++){
a1cc = str.charCodeAt(i);
a2cc = str.charCodeAt(i+1);
if(a1cc<a2cc){
flag = 1;
}
else{
flag = 0;
break;
}
}
if(flag === 1){
return true;
}
else{
return false;
}
}
Method 2
function alphabetSubsequence(str) {
const chars = str.split('');
const charCodes = chars.map((char) => char.charCodeAt(0));
if(new Set(charCodes).size !== charCodes.length) {
return false;
}
for (let i = 0; i < charCodes.length - 1; i++) {
if(charCodes[i] > charCodes[i + 1]) {
return false;
}
}
return true;
}
/**
* Test Suite
*/
describe('alphabetSubsequence()', () => {
it('returns false when it has duplicate letters', () => {
// arrange
const str = 'effg';
// act
const result = alphabetSubsequence(str);
// log
console.log("result 1: ", result);
// assert
expect(result).toBe(false);
});
it('returns false when NOT in ascending a - z order', () => {
// arrange
const str = 'cdce';
// act
const result = alphabetSubsequence(str);
// log
console.log("result 2: ", result);
// assert
expect(result).toBe(false);
});
it('returns true whenno duplicates and is ascending a - z order ', () => {
// arrange
const str = 'ace';
// act
const result = alphabetSubsequence(str);
// log
console.log("result 3: ", result);
// assert
expect(result).toBe(true);
});
});
COMMENTS