京東實習_字元矩陣中字串的匹配個數
阿新 • • 發佈:2022-03-23
輸入:輸入矩陣長/寬度n,和目標字串str,再 輸入n*n的字元矩陣;
求解:給出字元矩陣中 橫向和縱向匹配字串str的個數
1 #include<bits/stdc++.h> 2 using namespace std; 3 int main(){ 4 int n,res=0; 5 char ch; 6 string str; 7 cin >> n; 8 cin >>str; 9 vector<vector<char>> tab; 10 for (int i = 0; i < n;i++) 11 { 12 vector<char> s; 13 for (int j = 0; j < n;j++){ 14 cin >> ch; 15 s.push_back(ch); 16 } 17 tab.push_back(s); 18 } 19 int len = str.size(); 20 for (int i = 0; i < n;i++){ 21 for(int j = 0;j<n;j++){ 22 for (int k = 0; i+k < n ;k++){ //down 23 if(str[k]!=tab[i+k][j])break; 24 if(k==len-1){ 25 res++; 26 } 27 } 28 for (int k = 0; j+k < n;k++){ //right 29 if(str[k]!=tab[i][j+k])break; 30 if(k==len-1){ 31 res++; 32 } 33 } 34 } 35 } 36 cout << res; 37 return 0; 38 }
輸入:
3 abc xax abc xcx
輸出:
2
第二行和第二列都是 :abc
思想:暴力解法,遍歷每一個點