Pretty easy. Loops are formed if you have an even number of MF/FM tracks and an equal number of MM and FF tracks. Just check for both conditions to be true.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
*
* @author Sanchit M. Bhatnagar
* @see http://uhunt.felix-halim.net/id/74004
*
*/
public class P11586 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int[] count;
int N = Integer.parseInt(br.readLine().trim());
for (int zz = 0; zz < N; zz++) {
count = new int[] { 0, 0 };
StringTokenizer st = new StringTokenizer(br.readLine().trim());
while (st.hasMoreTokens()) {
String input = st.nextToken();
if (input.equals("MF") || input.equals("FM")) {
if (count[0] == 0)
count[0]++;
else
count[0]--;
} else {
if (input.equals("MM")) {
count[1]++;
} else {
count[1]--;
}
}
}
if (count[0] == 0 && count[1] == 0) {
out.println("LOOP");
} else {
out.println("NO LOOP");
}
}
out.close();
br.close();
}
}