我用的是笨办法,先遍历字符串,统计出向左和向右的次数,如果两次相同的话,则仍是面向北。如果向左或者向右次数多的话,则多出的部分对4求余就可以了。
#include <bits/stdc++.h> using namespace std; int main(){ int n; string s; int count=0; int sount=0; char left[] = {"NWSE"}; char right[] = {"NESW"}; int a=0; int b=0; cin >> n; cin >> s; for(int i=0; i<n; i++){ if(s[i]=='L'){ count++; } else if(s[i]=='R'){ sount++; } } if(count==sount){ cout << 'N' << endl; } else if(count>sount){ int ccount = count-sount; a = ccount%4; cout << left[a] << endl; } else if(count < sount){ int ssount = sount-count; b = ssount%4; cout << right[b] << endl; } }