This is the 19th day of my participation in the August Wenwen Challenge.More challenges in August
Medium difficult I am submissive, simple I punch attack!
8.19 – Reverse a vowel in a string
The question
Write a function that takes a string as input and inverts the vowels in that string.
Example 1:
Input: “hello” Output: “holle”
Input: “leetcode” Output: “leotcede”
Analysis of the
Iterate once to get the vowel character set and the subscript set of characters, iterate again to replace the subscript set
/ * * *@param {string} s
* @return {string}* /
var reverseVowels = function(s) {
let strArr = s.split(' ');
let vowels = 'aeiouAEIOU';
let vowelTmp = []; // Save vowel characters
let vowelIndex = []; // Save the subscript of the vowel character
for (let i = 0; i < strArr.length; i++) {
if (vowels.indexOf(strArr[i]) > -1) {
/ / vowel
vowelTmp.push(strArr[i]);
vowelIndex.push(i);
}
}
vowelTmp.reverse()
for (let j = 0; j < vowelIndex.length; j++) {
strArr.splice(vowelIndex[j], 1, vowelTmp[j])
}
return strArr.join(' ')};Copy the code
Complexity analysis
- Time complexity: O(n), n is the length of S, although traversed twice, but the sum is 2O(n), excluding the constant term is O(n)
- Space complexity:o(1)___, I don’t know
Running effect
8.17 – 551. Student attendance Record I
The question
You are given the string S to represent a student’s attendance record, each character of which is used to mark the day’s attendance (absence, lateness, presence). The record contains only the following three types of characters:
A student will receive an attendance award if he/she meets both of the following criteria:
In terms of total attendance, students are absent (‘A’) strictly less than two days. Students will not have a record of being late (‘L’) for 3 consecutive days or more.
Return true if the student can earn an attendance award; Otherwise, return false.
Analysis of the
If the condition is exceeded, return false; if the condition is not exceeded, return true
/ * * *@param {string} s
* @return {boolean}* /
var checkRecord = function(s) {
let a = 0;
let c = 0;
for (let i = 0 ; i < s.length; i++) {
let status = s[i]
// If the number of days absent from work does not match, pass the loop directly
if (status === 'A') {
a++
if (a >= 2) return false
}
// If the condition is not met for more than 3 consecutive days, pass the loop directly, otherwise need to reset, because the condition is broken
if (status === 'L') {
c++
if (c >= 3) return false
} else {
c = 0}}return true
};
Copy the code
### Complexity analysisCopy the code
- Time complexity: O (n), where n is the length of S
- Space complexity: O (1), EMMM, I do not know why O (1), please inform me if you know
Running effect
The summary of this chapter
✍ if there is anything wrong