Strings Flashcards

1
Q

Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

A
/**
 * @param {string} s
 * @return {string}
 */
var reverseWords = function(s) {
    return s.split(' ').reverse().filter(word => word).join(' ').trim();
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes.

Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase.

Given a non-empty string S and a number K, format the string according to the rules described above.

Example 1:
Input: S = “5F3Z-2e-9-w”, K = 4

Output: “5F3Z-2E9W”

Explanation: The string S has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.

Example 2:
Input: S = “2-5g-3-J”, K = 2

Output: “2-5G-3J”

Explanation: The string S has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.

A
/**
 * @param {string} S
 * @param {number} K
 * @return {string}
 */
var licenseKeyFormatting = function(S, K) {
    let S_ARR = S.split('-').join('').toUpperCase().split('');
    let res = [];
    for (let i = S_ARR.length; i >= 0; i -= K) {
        if (i - K >= 0) {
            res.push(S_ARR.slice(i - K, i).join(''));
        }
    }
    if (S_ARR.length % K !== 0) {
        res.push(S_ARR.slice(0, S_ARR.length % K).join(''));
    }
    return res.reverse().join('-');
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Implement atoi which converts a string to an integer.

Example 1:

Input: str = “42”
Output: 42
Example 2:

Input: str = “ -42”
Output: -42
Explanation: The first non-whitespace character is ‘-‘, which is the minus sign. Then take as many numerical digits as possible, which gets 42.
Example 3:

Input: str = “4193 with words”
Output: 4193
Explanation: Conversion stops at digit ‘3’ as the next character is not a numerical digit.

A
/**
 * @param {string} s
 * @return {number}
 */
var myAtoi = function(str) {
    if (str == null || str.length < 1)
		return 0;
	// trim white spaces
	str = str.trim();
let flag = '+';
	// check negative or positive
	let i = 0;
	if (str[0] == '-') {
		flag = '-';
		i++;
	} else if (str[0] == '+') {
		i++;
	}
	// use double to store result
	let result = 0;
	// calculate value
	while (str.length > i &amp;&amp; str[i] >= '0' &amp;&amp; str[i] <= '9') {
		result = result * 10 + (str[i] - '0');
		i++;
	}
if (flag == '-')
	result = -result;
	// handle max and min
	if (result > 2147483647)
		return 2147483647;
if (result < -2147483648)
	return -2147483648;

return result; };
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Convert a non-negative integer num to its English words representation.

Example 1:

Input: num = 123
Output: “One Hundred Twenty Three”
Example 2:

Input: num = 12345
Output: “Twelve Thousand Three Hundred Forty Five”

A

/**

  • @param {number} num
  • @return {string}
  • /
const belowTen = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"];
const belowTwenty = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
const belowHundred = ["", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
var numberToWords = function(num) {
    if (num == 0) {
        return "Zero";
    }
    return helper(num); 
};
var helper = function(num) {
    let result = "";
    if (num < 10) {
        result = belowTen[num];
    } else if (num < 20) {
        result = belowTwenty[num - 10];
    } else if (num < 100) {
        result = belowHundred[Math.floor(num/10)] + " " + helper(num % 10);
    } else if (num < 1000) {
        result = helper(Math.floor(num/100)) + " Hundred " +  helper(num % 100);
    } else if (num < 1000000) {
        result = helper(Math.floor(num/1000)) + " Thousand " +  helper(num % 1000);
    } else if (num < 1000000000) {
        result = helper(Math.floor(num/1000000)) + " Million " +  helper(num % 1000000);
    } else {
        result = helper(Math.floor(num/1000000000)) + " Billion " + helper(num % 1000000000);
    }
    return result.trim();
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:
Input: “Let’s take LeetCode contest”
Output: “s’teL ekat edoCteeL tsetnoc”
Note: In the string, each word is separated by single space and there will not be any extra space in the string.

A
/**
 * @param {string} s
 * @return {string}
 */
var reverseWord = function(word) {
    return word.split('').reverse().join('');
}
var reverseWords = function(s) {
    return s.split(' ').map(reverseWord).join(' ');
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
  1. Compare Version Numbers

Version numbers consist of one or more revisions joined by a dot ‘.’. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers.

To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1.

Return the following:

If version1 < version2, return -1.
If version1 > version2, return 1.
Otherwise, return 0.

A
/**
 * @param {string} version1
 * @param {string} version2
 * @return {number}
 */
var compareVersion = function(version1, version2) {
    const arr1 = version1.split(".");
    const arr2 = version2.split(".");
    let i = 0;
    while(i parseInt(arr2[i])){
                return 1;
            }
        } else if(i
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Input: input = “dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext”
Output: 20
Explanation: We have only one file and its path is “dir/subdir2/file.ext” of length 20.
The path “dir/subdir1” doesn’t contain any files.

A
/**
 * @param {string} input
 * @return {number}
 */
var lengthLongestPath = function(input) {
    let res = 0, n = input.length, level = 0;
    const m = [0];
    for (let i = 0; i < n; i++) {
        let start = i;
        while (i < n &amp;&amp; input[i] != '\n' &amp;&amp; input[i] != '\t') i++;
        if (i >= n || input[i] == '\n') {
            let t = input.substr(start, i - start);
            if (t.includes('.')) {
                res = Math.max(res, m[level] + t.length);
            } else {
                level++;
                m[level] = m[level - 1] + t.length + 1;
            }
            level = 0;
        } else {
            level++;
        }
    }
    return res;
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Input: “/home/”
Output: “/home”
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:

Input: “/../”
Output: “/”
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:

Input: “/home//foo/”
Output: “/home/foo”
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.

A
/**
 * @param {string} path
 * @return {string}
 */
var simplifyPath = function(path) {
    const stack =[];
    const p = path.split("/");
    for (const t of p) {
        if (stack.length &amp;&amp; t === "..") {
            stack.pop();
        } else if (t !== "." &amp;&amp; t !== "" &amp;&amp; t !== "..") {
            stack.push(t);
        }
    }
    return "/" + stack.join("/");
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
  1. Remove Comments
A
/**
 * @param {string[]} source
 * @return {string[]}
 */
var removeComments = function(source) {
    const res = [];
    let sb = '';     
    let mode = false;
    for (const s of source) {
        for (let i = 0; i < s.length; i++) {
            if (mode) {
                if (s[i] == '*' &amp;&amp; i < s.length - 1 &amp;&amp; s[i + 1] == '/') {
                        mode = false;
                        i++;        //skip '/' on next iteration of i
                    }
                }
                else {
                    if (s[i] == '/' &amp;&amp; i < s.length - 1 &amp;&amp; s[i + 1] == '/') {
                        break;      //ignore remaining characters on line s
                    }
                    else if (s[i] == '/' &amp;&amp; i < s.length - 1 &amp;&amp; s[i + 1] == '*') {
                        mode = true;
                        i++;           //skip '*' on next iteration of i
                    }
                    else    sb += s[i];     //not a comment
                }
            }
            if (!mode &amp;&amp; sb.length > 0) {
                res.push(sb);
                sb = '';   //reset for next line of source code
            }
        }
        return res;
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.

We would like to convert the sentence to “Goat Latin” (a made-up language similar to Pig Latin.)

The rules of Goat Latin are as follows:

If a word begins with a vowel (a, e, i, o, or u), append “ma” to the end of the word.
For example, the word ‘apple’ becomes ‘applema’.

If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add “ma”.
For example, the word “goat” becomes “oatgma”.

Add one letter ‘a’ to the end of each word per its word index in the sentence, starting with 1.
For example, the first word gets “a” added to the end, the second word gets “aa” added to the end and so on.
Return the final sentence representing the conversion from S to Goat Latin.

A
/**
 * @param {string} S
 * @return {string}
 */
var toGoatLatin = function(S) {
    const vowel = {};
    const vowerls_arr = 'aeiouAEIOU'.split('');
    for(const c of vowerls_arr) {
        vowel[c] = 1;
    }
    let ans = '';
    let ending = "a";
    for(const word of S.split(" ")) {
        const first = word[0];
        if(vowel[first]) {
            ans += word;
        } else {
            ans += word.substring(1, word.length);
            ans += first;
        }
        ans += "ma" + ending + " ";
        ending += "a";
    }
return ans.substring(0, ans.length - 1); };
How well did you know this?
1
Not at all
2
3
4
5
Perfectly