รับสตริงสตริงที่มีตัวอักษรภาษาอังกฤษ เป้าหมายคือการหาจำนวนสระที่เกิดขึ้นในสตริงย่อยทั้งหมดของ str หากสตริงเป็น "abcde" สตริงย่อยจะเป็น "a", "b", "c", "d", "e", "ab", "bc", "cd", "de", "abc", “bcd”, “cde”, “abcd”, “bcde”, “abcde” จำนวนสระในสตริงย่อยเหล่านี้คือ 10 (a และ e)
ตัวอย่าง
อินพุต
str = ”aloe”
ผลลัพธ์
Count the number of vowels occurring in all the substrings of given string are: 14
คำอธิบาย
The substrings are: “a”, “l”, “o”, “e”, “al”, “lo”, “oe”, “alo”, “loe”, “aloe”. Total vowels in these are: 14
อินพุต
str=”http”
ผลลัพธ์
Count the number of vowels occurring in all the substrings of given string are: 0
คำอธิบาย
The substrings are: “h”, “t”, “t”, “p”, “ht”, “tt”, “tp”, “htt”, “ttp”, “http”. Total vowels in these are: 0
แนวทางที่ใช้ในโปรแกรมด้านล่างมีดังนี้ −
ในแนวทางนี้ เราจะสร้าง vector vec ซึ่งเก็บจำนวนการเกิดขึ้นของอักขระ ith ในสตริงย่อยทั้งหมดใน vec[i]
อักขระตัวที่ 0 เกิดขึ้นในสตริงย่อย n โดยที่ n คือความยาวของสตริง str
อักขระ ith เกิดขึ้นในสตริงย่อยทั้งหมดที่มี ( n−i ) + จำนวนสตริงย่อยที่มีอักขระ ith เช่นเดียวกับอักขระก่อนหน้า ( arr[ i-1 ] ) - จำนวนของสตริงย่อยที่เกิดจากอักขระก่อนหน้าเท่านั้น ( i )
-
รับสตริงสตริงเป็นอินพุต
-
ฟังก์ชั่น substring_vowels_count(string str, int length) ใช้ str กับความยาวและคืนค่าจำนวนสระที่เกิดขึ้นในสตริงย่อยทั้งหมดของสตริงที่กำหนด
-
นับเริ่มต้นเป็น 0
-
หาเวกเตอร์จำนวนเต็ม vec
-
ข้ามผ่าน vec โดยใช้ for loop จาก i-0 ถึง i
-
ถ้า i=0 สำหรับอักขระตัวที่ 0 จะนับเป็นความยาว ตั้งค่า vec[0]=length โดยใช้push_back[length].
-
สำหรับอักขระอื่นๆ ทั้งหมดที่ตั้งค่าโดยใช้ push_back(temp_1 + temp_2) wheretemp_1=length−1 และ temp_2=vec[i−1]−i.
-
ตอนนี้สำรวจ str อีกครั้งโดยใช้ for loop และสำหรับแต่ละ str[i] เป็นสระ ( a , e, i, o หรือ u ) เพิ่ม vec[i] เพื่อนับ
-
ในตอนท้ายเราจะมีจำนวนสระในสตริงย่อยเป็นจำนวนที่เกิดขึ้นทั้งหมด
-
ผลตอบแทนนับเป็นผลลัพธ์
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int substring_vowels_count(string str, int length){
int count = 0;
vector<int> vec;
for (int i = 0; i < length; i++){
if (i == 0){
vec.push_back(length);
} else {
int temp_1 = length − i;
int temp_2 = vec[i − 1] − i;
vec.push_back(temp_1 + temp_2);
}
}
for (int i = 0; i < length; i++){
if(str[i] == 'a' || str[i] == 'i' || str[i] == 'e' || str[i] == 'o' || str[i] == 'u'){
count = count + vec[i];
}
}
return count;
}
int main(){
string str = "honesty";
int length = str.length();
cout<<"Count the number of vowels occurring in all the substrings of given string are: "<<substring_vowels_count(str, length);
return 0;
} ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น มันจะสร้างผลลัพธ์ต่อไปนี้ -
Count the number of vowels occurring in all the substrings of given string are: 28