Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Maximum power of jump required to reach the end of string in C++


ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมหาพลังกระโดดสูงสุดที่จำเป็นเพื่อไปถึงท้ายสตริง

เราจะได้รับสตริงของ 0 และ 1 งานคือหาการกระโดดสูงสุดที่ต้องใช้เพื่อเคลื่อนที่จากหน้าสู่หลังสตริง โดยที่สามารถเคลื่อนที่ไปยังองค์ประกอบเดียวกับปัจจุบันได้

ตัวอย่างโค้ด

#include <bits/stdc++.h>
using namespace std;

int powerOfJump(string s) {
    int count = 1;
    int max_so_far = INT_MIN;
    char ch = s[s.length() - 1];
    for (int i = 0; i < s.length(); i++) {
        if (s[i] == ch) {
            if (count > max_so_far) max_so_far = count;
            count = 1;
        } else count++;
    }
    return max_so_far;
}

int main() {
    string st = "1010101";
    cout << powerOfJump(st);
}

เอาต์พุต

2