เราได้รับสตริงตัวอักษรและงานคือการคำนวณจำนวนคู่ตัวอักษรที่มีระยะห่างเท่ากับที่เรามีในอักษรอังกฤษ
อินพุต − string str = 'Tutorials Point'
เอาต์พุต − นับคู่ตัวอักษรที่มีระยะห่างเท่ากับในอักษรอังกฤษคือ: 5
คำอธิบาย − คู่ตัวอักษรที่มีระยะห่างเท่ากับในอักษรอังกฤษคือ (u, t), (u, r), (t, r), (i, o) และ (s, n) รวมทั้งหมด 5 คู่
อินพุต − string str = 'Learning is the best habit'
เอาต์พุต − นับคู่ตัวอักษรที่มีระยะห่างเท่ากับในอักษรอังกฤษคือ: 12
คำอธิบาย − คู่ตัวอักษรที่มีระยะห่างเท่ากับในอักษรอังกฤษคือ (r, i), (r, h), (n, i), (n, b), (i, g), (n, t), (g, i), (i, b), (s, h), (h, t), (s, t) และ (a, b) รวมทั้งหมด 12 คู่
วิธีการที่ใช้ในโปรแกรมด้านล่าง
รับสตริงตัวอักษรและส่งข้อมูลไปยังฟังก์ชัน
ใช้ตัวแปรชั่วคราว count เพื่อเก็บจำนวนคู่ที่สามารถสร้างได้
คำนวณความยาวของสตริงด้วยฟังก์ชัน length()
เริ่มลูป FOR จาก i = 0 ถึงความยาวของสตริง
ภายในลูป เริ่มลูป FOR อีกอันจาก j = i+1 ถึงความยาวของสตริง
ภายในลูป ตั้ง temp เป็น abs(str[i] - str[j])
ตรวจสอบ IF temp == abs(i-j) แล้วเพิ่ม count ขึ้น 1
คืนค่า count
พิมพ์ผลลัพธ์
ตัวอย่าง
#include <bits/stdc++.h> using namespace std; int pairs_distance(string str){ int count = 0; int len = str.length(); for (int i = 0; i < len; i++){ for (int j = i + 1; j < len; j++){ int temp = abs(str[i] - str[j]); if (temp == abs(i - j)){ count++; } } } return count; } int main(){ string str = "Tutorials Point"; cout<<"Count of character pairs at same distance as in English alphabets are: "<<pairs_distance(str); return 0; }เอาต์พุต
ถ้าเรารันโค้ดด้านบนจะได้ผลลัพธ์ดังนี้ −
Count of character pairs at same distance as in English alphabets are: 5