A lot of people associate Logo programming language with turtle graphics. In this case the turtle moves along the straight line and accepts commands "T" ("turn around") and "F" ("move 1 unit forward").You are given a list of commands that will be given to the turtle. You have to change exactly n commands from the list (one command can be changed several times). How far from the starting point can the turtle move after it follows all the commands of the modified list?

The first line of input contains a string commands — the original list of commands. The string commands contains between 1 and 100 characters, inclusive, and contains only characters "T" and "F". The second line contains an integer n (1 ≤ n ≤ 50) — the number of commands you have to change in the list.

Output the maximum distance from the starting point to the ending point of the turtle's path. The ending point of the turtle's path is turtle's coordinate after it follows all the commands of the modified list.

NoteIn the first example the best option is to change the second command ("T") to "F" — this way the turtle will cover a distance of 2 units.In the second example you have to change two commands. One of the ways to cover maximal distance of 6 units is to change the fourth command and first or last one.

import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;

import static java.lang.Math.*;

public class AC {

    //solve by Fdg (it's good solve)

    int [][][][] d;
    int l;
    char [] c ;
    public void solve() throws IOException {

        c = in.readLine().toCharArray();
        int n  = readInt();
        l = c.length;
        d = new int [202][l+2][n+2][2];
        for (int i =0; i<202;i++){
            for (int j =0; j<l+2;j++){
                for(int k = 0; k<n+2; k++){
                    for (int q = 0; q<2; q++){
                        d[i][j][k][q] = -1;
                    }
                }
            }
        }
        out.print(rec(100,0,n,0));
    }

    int rec (int pos,int step,int left,int cource ){

        if(d[pos][step][left][cource]!=-1) {
            return d[pos][step][left][cource];
        }
        if (step==l){
            if ((left&1)>0){
                return 0;
            }
            return abs(pos-100);
        }
        int way=0;
        if (cource==0){
            way++;
        }
        else way--;
        int ans = 0;
        if (c[step]=='F'){
            ans = max(ans,rec(pos+way,step+1,left,cource));
        }
        if (c[step] == 'T'){
            ans = max(ans,rec(pos,step+1,left,cource^1));
        }
        if (left>0){
            if (c[step]=='F'){
                ans = max(ans,rec(pos,step+1,left-1,cource^1));
            }
            if (c[step]=='T'){
                ans = max(ans,rec(pos+way,step+1,left-1,cource));
            }
        }
        return d[pos][step][left][cource] = ans;

    }

    // ===========================================================================
    final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

    void init() throws FileNotFoundException {
        if (ONLINE_JUDGE) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        } else {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        }
    }

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            tok = new StringTokenizer(in.readLine());
        }
        return tok.nextToken();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }

    public static void main(String[] args) {
        new AC().run();
    }

    public void run() {
        try {
            long t1 = System.currentTimeMillis();
            init();
            solve();
            out.close();
            long t2 = System.currentTimeMillis();
            System.err.println("Time = " + (t2 - t1));
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }

}

import java.util.*;
import java.math.*;
import java.io.*;

import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;

public class  Main  {

	//ArrayList<Integer> lis = new ArrayList<Integer>();
	//ArrayList<String> lis = new ArrayList<String>();
	//ArrayList<test> lis = new ArrayList<test>();
//	static long sum=0;
//	static boolean f=false;
	//static String s[],r="";
//	static int dx[]={1,-1,0,0};
	//static int dy[]={0,0,1,-1};
	static int dp[][][][],co,r=0;
	static String s;

public  static void main(String[] args) throws IOException {
   //googlein.txt C-small-attempt0.in
//	Scanner sc =new Scanner(new File("file.txt"));
	 Scanner sc =new Scanner(System.in);
	  //File file = new File("file.txt");
	//	PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
	//	sc.useDelimiter("(\\s)+|[,]");

	  while(sc.hasNext()){
		   //long sum=0;
	//	  int n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt();
		r=0;
	    s=sc.next();
	    co=sc.nextInt();
	    dp=new int[s.length()][co+1][202][2];
	for(int i=0;i<s.length();i++)
		for(int t=0;t < co+1;t++)for(int u=0;u <202 ;u++){ dp[i][t][u][0]=dp[i][t][u][1]=-1;  }

		dfs(0,0,0,0);

		System.out.println(r);

	  }

}

	// db("Case #"+(k)+": "+c);
	 //	pw.println("Case #"+(k)+": "+c);

	 	//pw.flush();
	 	//pw.close();

    static int dfs(int x,int y,int d,int n){

       if( -1<dp[x][y][101+n][d])return dp[x][y][abs(n)][d];

    //    db(x,y,d,n,"FI");

        if( co==y ){
        	for(int i=x;i<s.length();i++){ if(s.charAt(i)=='F')n= d==0? n+1:n-1; else d= d==0 ? 1:0;  }
        	return n;
        }

    	if( x+1==s.length() ){
    		Character c=s.charAt(s.length()-1);
    		if(  (co-y)%2==0 ){ if(c=='F')n= d==0? n+1:n-1;   }
    		else { if(c=='T')n= d==0? n+1:n-1;   }
    		return n;
    	}

    	int a=0,b=0;
    	if( s.charAt(x)=='F' ){    if(d==0){ a=dfs(x+1,y,d,n+1); b=dfs(x+1,y+1,d+1,n ); }
    	                           else { a=dfs(x+1,y,d,n-1); b=dfs(x+1,y+1,d-1,n ); }
    	}

    	else { if(d==0){ a=dfs(x+1,y,d+1,n); b=dfs(x+1,y+1,d,n+1 ); }
    	          else { a=dfs(x+1,y,d-1,n); b=dfs(x+1,y+1,d,n-1 ); }
    	}

    	//  db(x,y,d,n);

    	//db(a,b,x,y,d,n);
    	dp[x][y][101+n][d] =  max(abs(a),abs(b));

    	r = max(dp[x][y][101+n][d],r);
    	return dp[x][y][101+n][d];

    }

    static void db(Object... os){
	         System.err.println(Arrays.deepToString(os));

	}

}

/*class P implements Comparable<P>{
    int v,vv,t;
	P(int v,int vv,int t){
		this.v=v;
	    this.vv=vv;
	    this.t=t;
	}
	  public int compareTo(P x){
          return t-x.t;
	   }

}*/

import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Fantast
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		Scanner in = new Scanner(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskE solver = new TaskE();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskE {
    int n;
    char[] s;
    public void solve(int testNumber, Scanner in, PrintWriter out) {
        s = in.next().toCharArray();
        n = in.nextInt();

        for (int i = 0; i < 101; ++i) {
            for (int j = 0; j < 2; ++j) {
                for (int k = 0; k < 101; ++k) {
                    mxs[i][j][k] = -1;
                    mns[i][j][k] = -1;
                }
            }
        }

        out.println(
                mx(
                        Math.abs(mxdist(0, 1, n)),
                        Math.abs(mndist(0, 1, n)),
                        Math.abs(mxdist(0, -1, n)),
                        Math.abs(mndist(0, -1, n))
                ));
    }

    private int mx(int... a) {
        int res = a[0];
        for (int n : a) {
            res = Math.max(res, n);
        }
        return res;
    }

    int mxs[][][] = new int[101][2][101];
    public int mxdist(int ind, int dir, int tochange) {
        if (ind == s.length) {
            if (tochange > s.length - ind) {
                return Integer.MIN_VALUE / 2;
            }
            return 0;
        }

        int di = (dir+1)/2;
        if (mxs[ind][di][tochange] != -1) {
            return mxs[ind][di][tochange];
        }

        int res;
        if (s[ind] == 'T') {
            res = Integer.MIN_VALUE / 2;
            for (int dc = 0; dc <= tochange; ++dc) {
                if (dc%2 == 0) {
                    res = Math.max(res, mxdist(ind + 1, -dir, tochange - dc));
                } else {
                    res = Math.max(res, dir + mxdist(ind + 1, dir, tochange - dc));
                }
            }
        } else {
            res = Integer.MIN_VALUE / 2;
            for (int dc = 0; dc <= tochange; ++dc) {
                if (dc%2 == 0) {
                    res = Math.max(res, dir + mxdist(ind + 1, dir, tochange - dc));
                } else {
                    res = Math.max(res, mxdist(ind + 1, -dir, tochange - dc));
                }
            }
        }

        return mxs[ind][di][tochange] = res;
    }

    int mns[][][] = new int[101][2][101];
    public int mndist(int ind, int dir, int tochange) {
        if (ind == s.length) {
            if (tochange > s.length - ind) {
                return Integer.MAX_VALUE / 2;
            }
            return 0;
        }

        int di = (dir+1)/2;
        if (mns[ind][di][tochange] != -1) {
            return mns[ind][di][tochange];
        }

        int res;
        if (s[ind] == 'T') {
            res = Integer.MAX_VALUE / 2;
            for (int dc = 0; dc <= tochange; ++dc) {
                if (dc%2 == 0) {
                    res = Math.min(res, mndist(ind + 1, -dir, tochange - dc));
                } else {
                    res = Math.min(res, dir + mndist(ind + 1, dir, tochange - dc));
                }
            }
        } else {
            res = Integer.MAX_VALUE / 2;
            for (int dc = 0; dc <= tochange; ++dc) {
                if (dc%2 == 0) {
                    res = Math.min(res, dir + mndist(ind + 1, dir, tochange - dc));
                } else {
                    res = Math.min(res, mndist(ind + 1, -dir, tochange - dc));
                }
            }
        }
        return mns[ind][di][tochange] = res;
    }
}

import java.util.Scanner;

public class C132 {
	public static void main(String[] args) throws Exception {
		Scanner in = new Scanner(System.in);
		a = in.nextLine();
		int n = in.nextInt();
		dp = new int[2][a.length()][n + 1];
		for (int x = 0; x < a.length(); x++) {
			for (int y = 0; y < n + 1; y++) {
				dp[0][x][y] = dp[1][x][y] = NULL;
			}
		}
		int a = max(0, n, 0);
		int b = -max(0, n, 1);
		System.out.println(a > b ? a : b);
	}

	static int max(int start, int swaps, int f) {
		if (swaps < 0)
			return NULL2;
		if (start == a.length()) {
			if (swaps % 2 == 0)
				return 0;
			else
				return NULL2;
		}
		if (dp[f][start][swaps] == NULL) {
			int n, k, j;
			if (a.charAt(start) == 'F') {
				k = max(start + 1, swaps, f);
				n = k + 1;
				j = -max(start + 1, swaps - 1, 1 - f);
			} else {
				j = -max(start + 1, swaps, 1 - f);
				k = max(start + 1, swaps - 1, f);
				n = k + 1;
			}
			boolean b= j>n;
			if(f==1) b = !b;
			if (isnull(k) || (!isnull(j) && b)) {
				dp[f][start][swaps] = j;
			} else
				dp[f][start][swaps] = n;
		}

		return dp[f][start][swaps];
	}

	static boolean isnull(int k) {
		return k == NULL2 || k == -NULL2;
	}

	static int NULL = 6969;
	static int NULL2 = 696969;
	static String a;
	static int[][][] dp;
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class C132 {
	static char[] com;
	static int[][][][][] mem;
	public static void main(String[] args) throws IOException{
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

		com = bf.readLine().toCharArray();

		int n = Integer.parseInt(bf.readLine());
		mem = new int[2][2][n+1][com.length][200];

		for(int[][][][] a:mem)
			for(int[][][] a2:a)
				for(int[][] a3:a2)
					for(int[] a4:a3)
						Arrays.fill(a4, -101);

		System.out.println(Math.abs(dp(0,0,n,0,0)));
	}
	static int dp(int dir, int changed,int n, int idx, int curD){
		if(idx==com.length)
			return n==0?0:-(int)1e9;

		int[][][][][] a = mem;

		if(mem[dir][changed][n][idx][curD+99]!=-101)
			return mem[dir][changed][n][idx][curD+99];

		int ans = 0;
		if((com[idx]=='F'&&changed==0)||(com[idx]=='T'&&changed==1))
		{
			if(Math.abs(dp(dir,0,n,idx+1, curD+(dir==0?1:-1)))<=1000)
				ans = (dir==0?1:-1)+dp(dir,0,n,idx+1,curD+(dir==0?1:-1));
		}
		else
		{
			if(Math.abs(dp(dir==0?1:0, 0, n, idx+1,curD))<=1000)
				ans = dp(dir==0?1:0, 0, n, idx+1,curD);
		}

		if(n>0&&Math.abs(curD+dp(dir, changed==0?1:0, n-1, idx,curD))>Math.abs(curD+ans)&&Math.abs(dp(dir, changed==0?1:0, n-1, idx,curD))<=1000)
			ans = dp(dir, changed==0?1:0, n-1, idx, curD);

		return mem[dir][changed][n][idx][curD+99] = ans;
	}
}

import java.util.Arrays;
import java.util.Scanner;

public class F {
    static int[][][][] dp = new int[110][230][110][3];
    static String inp;

    public static int min(int index, int pos, int n, int direction) {
        if (index == inp.length() && n == 0)
            return Math.abs(pos);
        else if (index == inp.length())
            return Integer.MIN_VALUE;
        else if (dp[index][pos + 100][n][direction + 1] != -1)
            return dp[index][pos + 100][n][direction + 1];
        else {
            if (n == 0) {
                if (inp.charAt(index) == 'T') {
                    return dp[index][pos + 100][n][direction + 1] = min(
                            index + 1, pos, n, -direction);
                } else
                    return dp[index][pos + 100][n][direction + 1] = min(
                            index + 1, pos + direction, n, direction);
            }

            else {
                if (inp.charAt(index) == 'T') {
                    int max = min(index + 1, pos, n, -direction);
                    for (int i = 1; i <= n; i++) {
                        if (i % 2 == 0) {
                            max = Math.max(max,
                                    min(index + 1, pos, n - i, -direction));
                        } else {
                            max = Math.max(
                                    min(index + 1, pos + direction, n - i,
                                            direction), max);
                        }
                    }
                    return dp[index][pos + 100][n][direction + 1] = max;

                } else {
                    int max = min(index + 1, pos + direction, n, direction);
                    for (int i = 1; i <= n; i++) {
                        if (i % 2 == 0) {
                            max = Math.max(
                                    max,
                                    min(index + 1, pos + direction, n - i,
                                            direction));
                        } else {
                            max = Math.max(max,
                                    min(index + 1, pos, n - i, -direction));
                        }
                    }
                    return dp[index][pos + 100][n][direction + 1] = max;
                }
            }
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        inp = in.nextLine();

        int n = in.nextInt();
        for (int i = 0; i < dp.length; i++)
            for (int j = 0; j < dp[i].length; j++)
                for (int k = 0; k < dp[i][j].length; k++)
                    Arrays.fill(dp[i][j][k], -1);
        System.out.println(min(0, 0, n, 1));
    }
}

import java.io.*;
import java.util.StringTokenizer;

public class main132C {
    public static PrintWriter out = new PrintWriter(System.out);
    public static FastScanner enter = new FastScanner(System.in);

    public static void main(String[] args) throws IOException {
        solve();
        out.close();
    }
    static String s;
    static int n;
    static int dpleft[][][][];
    static int dprigth[][][][];
    static boolean was[][][][];
    private static void solve() throws IOException {
        s=enter.next();
        StringBuilder imstupidtard=new StringBuilder();
        for (int i = 0; i <s.length() ; i++) {
            if(s.charAt(i)=='T') imstupidtard.append('F');
            else imstupidtard.append('T');
        }
        s=imstupidtard.toString();
        n=enter.nextInt();
        dpleft=new int[s.length()+1][n+1][2][2];
        dprigth=new int[s.length()+1][n+1][2][2];
        was=new boolean[s.length()+1][n+1][2][2];
        mem(0,n, 1, 0);
        out.println(Math.max(Math.abs(dprigth[0][n][1][0]),Math.abs(dpleft[0][n][1][0])));
    }

    private static void mem(int pos, int needChange, int way, int waschanged) {
        if(was[pos][needChange][way][waschanged]) return;
        if(pos==s.length()){
            if(needChange==0){
                dpleft[pos][0][way][waschanged]=0;
                dprigth[pos][0][way][waschanged]=0;
            }
            else{
                dpleft[pos][needChange][way][waschanged]=100;
                dprigth[pos][needChange][way][waschanged]=-100;
            }
            was[pos][needChange][way][waschanged]=true;
            return;
        }
        //dont change this
        mem(pos+1, needChange, ((s.charAt(pos)=='F' && waschanged==0)||(s.charAt(pos)=='T' && waschanged==1))?(1-way):way,0);
        //change this
        if(needChange>=1)mem(pos, needChange-1,way,1-waschanged);

        int firstDelta=dprigth[pos+1][needChange][((s.charAt(pos)=='F' && waschanged==0)||(s.charAt(pos)=='T' && waschanged==1))?(1-way):way][0];
        int secondDelta=(needChange>=1)?dprigth[pos][needChange-1][way][1-waschanged]:-100;
        dprigth[pos][needChange][way][waschanged]=Math.max(
                (firstDelta==-100)?firstDelta:(firstDelta+func(pos, way, waschanged)),
                (needChange>=1)?secondDelta:-100);
         firstDelta=dpleft[pos+1][needChange][((s.charAt(pos)=='F' && waschanged==0)||(s.charAt(pos)=='T' && waschanged==1))?(1-way):way][0];
         secondDelta=(needChange>=1)?dpleft[pos][needChange-1][way][1-waschanged]:100;
        dpleft[pos][needChange][way][waschanged]=Math.min((firstDelta==100)?firstDelta:(firstDelta+func(pos, way, waschanged)),
                (needChange>=1)?secondDelta:100);

        was[pos][needChange][way][waschanged]=true;
    }

    private static int func(int pos, int way, int waschanged) {
        if(s.charAt(pos)=='F'){
            if(waschanged==0) return 0;
            else{
                if(way==1) return 1;
                else return -1;
            }
        }
        else{
            if(waschanged==0){
                if(way==1) return 1;
                else return -1;
            }
            else{
                return 0;
            }
        }
    }

    static class FastScanner {
        BufferedReader br;
        StringTokenizer stok;

        FastScanner(InputStream is) {
            br = new BufferedReader(new InputStreamReader(is));
        }

        String next() throws IOException {
            while (stok == null || !stok.hasMoreTokens()) {
                String s = br.readLine();
                if (s == null) {
                    return null;
                }
                stok = new StringTokenizer(s);
            }
            return stok.nextToken();
        }

        int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        double nextDouble() throws IOException {
            return Double.parseDouble(next());
        }

        char nextChar() throws IOException {
            return (char) (br.read());
        }

        String nextLine() throws IOException {
            return br.readLine();
        }
    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.util.*;
import java.lang.*;

/**
 *
 * @author Bryan AW
 */
public class Codeforces {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args){

        //Logo Turtle

        Scanner sc=new Scanner(System.in);

        String s=sc.next();

        int len=s.length();

        int n=sc.nextInt();

        int t=0;

        for (char c : s.toCharArray()){
            if (c=='T'){
                t++;
            }
        }

        int ans;

        if (n==t){
            ans=len;
        }
        else if (n>t){
            int left=n-t;
            ans=len-left%2;
        }
        else {
            int[][][] dp=new int[len+1][n+1][2];
            for (int i=0;i<=len;i++){
                for (int j=0;j<=n;j++){
                    dp[i][j][0]=-999;
                    dp[i][j][1]=-999;
                }
            }
            dp[0][0][0]=0;
            dp[0][0][1]=0;
            for (int i=1;i<=len;i++){
                for (int j=0;j<=n;j++){
                    for (int k=0;k<=j;k++){
                        if (s.charAt(i-1)=='F'){
                            if (k%2==0){
                                dp[i][j][0]=Math.max(dp[i][j][0], dp[i-1][j-k][0]+1);
                                dp[i][j][1]=Math.max(dp[i][j][1], dp[i-1][j-k][1]-1);
                            }
                            else {
                                dp[i][j][0]=Math.max(dp[i][j][0], dp[i-1][j-k][1]);
                                dp[i][j][1]=Math.max(dp[i][j][1], dp[i-1][j-k][0]);
                            }
                        }
                        else {
                            if (k%2==0){
                                dp[i][j][0]=Math.max(dp[i][j][0], dp[i-1][j-k][1]);
                                dp[i][j][1]=Math.max(dp[i][j][1], dp[i-1][j-k][0]);
                            }
                            else {
                                dp[i][j][0]=Math.max(dp[i][j][0], dp[i-1][j-k][0]+1);
                                dp[i][j][1]=Math.max(dp[i][j][1], dp[i-1][j-k][1]-1);
                            }
                        }
                    }
                }
            }
            ans=Math.max(dp[len][n][0], dp[len][n][1]);
        }

        System.out.println(ans);

    }

}

import java.util.*;

public class O {

    static int len, n;
    static int[][][][] dp = new int[2][200][500][100]; ///base is 200;
    static boolean[][][][] vis = new boolean[2][200][500][100];
    static String cmd;

    static int dfs(int dir, int cd, int pos, int cur) {

        if (cur < 0) return 0;
        if (cd == len) {
            if (cur > 0) return 0;
            else return Math.abs(pos - 200);
        }

        if (vis[dir][cd][pos][cur] == true)
            return dp[dir][cd][pos][cur];
        int ret = 0;

        int mv = (dir == 1) ? -1 : 1;

        if (cmd.charAt(cd) == 'T')
            ret = Math.max(ret, Math.max(dfs(1 ^ dir, cd + 1, pos, cur), dfs(dir, cd + 1, pos + mv, cur - 1)));
        else if (cmd.charAt(cd) == 'F')
            ret = Math.max(ret, Math.max(dfs(dir, cd + 1, pos + mv, cur), dfs(1 ^ dir, cd + 1, pos, cur - 1)));

        vis[dir][cd][pos][cur] = true;
        dp[dir][cd][pos][cur] = ret;

        return ret;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        cmd = in.nextLine();
        len = cmd.length();

        n = in.nextInt();

        int ans = -999999;
        for (int i = n; i >= 0; i -= 2) {
            ans = Math.max(ans, dfs(0, 0, 200, i));
        }

        System.out.println(ans);
    }
}

import java.util.Scanner;

public class Turtle {
	int size ;
	int[][][][] dp ;
	String word ;

	int solve(int index , int position , int changes , int direction) {
		if(changes < 0)
			return -1<< 28 ;

		if(index == size) {
			if(changes % 2 == 0)
				return Math.abs(position) ;
			else
				return Math.abs(position) - 1 ;
		}

		if(dp[index][changes][position+100][direction] != -1)
			return dp[index][changes][position+100][direction] ;
		int way1 , way2 ;

		if(word.charAt(index) == 'F') {
			way1 = solve(index+1 , position +  (direction == 0 ? 1 : -1) , changes , direction ) ;
				way2 = solve(index+1 , position , changes-1 , direction ^ 1) ;
			}

		else {

			way1 = solve(index+1 , position , changes , direction ^ 1);
			way2 =solve(index+1 , position+  (direction == 0 ? 1 : -1) , changes-1 , direction ) ;
		}

		return dp[index][changes][position+100][direction] = Math.max(way1, way2);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner Scan = new Scanner(System.in);
		Turtle tr = new Turtle();
		String command = Scan.next() ;
		int changes = Scan.nextInt() ;
		tr.size = command.length() ;
		tr.word = command ;
		tr.dp = new int [100][100][200][2];
		for(int i = 0 ; i < 100 ; i++)
			for(int j = 0 ; j<100 ; j++)
				for(int k = 0 ; k< 200 ; k++)
					for(int l= 0 ; l< 2 ; l++)
						tr.dp[i][j][k][l] = -1 ;

		System.out.println(tr.solve(0 , 0 , changes , 0));

	}

}

import java.io.*;
import java.util.*;

public class I1 {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        input = sc.next();
        int n = Integer.parseInt(sc.next());
        int right = countA1(0, 0, n);
        int left = countB1(0, 0, n);
        System.out.println(Math.max(right, left));
    }

    static int countB1(int x, int y, int z){
        if(Y[x][y][z]>0){
            return B[x][y][z];
        }
        if(y>=input.length() && z!=0){
            return Integer.MAX_VALUE;
        }
        if(y>=input.length()){
            return 0;
        }
        if(z==0){
            int dir = 1, distance = 0;
            if(x==0) dir = -1;
            for(int i=y; i<input.length(); i++){
                if(input.charAt(i)=='T') dir = -dir;
                else distance += dir;
            }
            B[x][y][z] = distance;
            Y[x][y][z] = 1;
            return distance;
        }
        int best = Integer.MIN_VALUE;
        for(int i=z; i>=0; i-=2){
            char ch = input.charAt(y);
            int dir = 1; if(x==0) dir = -1;
            int dist = 0;
            int x1;
            if(ch=='F'){
                dist += dir;
                x1 = x;
            }
            else{
                dir = -dir;
                x1 = 1-x;
            }
            int curr = countB1(x1, y+1, i);
            if(-105<=curr && curr<=105) best = Math.max(best, dist+curr);
        }
        for(int i=z-1; i>=0; i-=2){
            char ch = input.charAt(y);
            int dir = 1; if(x==0) dir = -1;
            int dist = 0;
            int x1;
            if(ch=='T'){
                dist += dir;
                x1 = x;
            }
            else{
                dir = -dir;
                x1 = 1-x;
            }
            int curr = countB1(x1, y+1, i);
            if(-105<=curr && curr<=105) best = Math.max(best, dist+curr);
        }
        Y[x][y][z] = 1;
        B[x][y][z] = best;
        if(-105<=best && best<=105) B[x][y][z] = best;
        else B[x][y][z] = Integer.MAX_VALUE;
        return B[x][y][z];
    }

    static int countA1(int x, int y, int z){
        if(X[x][y][z]>0){
            return A[x][y][z];
        }
        if(y>=input.length() && z!=0){
            return Integer.MAX_VALUE;
        }
        if(y>=input.length()){
            return 0;
        }
        if(z==0){
            int dir = 1, distance = 0;
            if(x==1) dir = -1;
            for(int i=y; i<input.length(); i++){
                if(input.charAt(i)=='T') dir = -dir;
                else distance += dir;
            }
            A[x][y][z] = distance;
            X[x][y][z] = 1;
            return distance;
        }
        int best = Integer.MIN_VALUE;
        for(int i=z; i>=0; i-=2){
            char ch = input.charAt(y);
            int dir = 1; if(x==1) dir = -1;
            int dist = 0;
            int x1;
            if(ch=='F'){
                dist += dir;
                x1 = x;
            }
            else{
                dir = -dir;
                x1 = 1-x;
            }
            int curr = countA1(x1, y+1, i);
            if(-105<=curr && curr<=105){
                best = Math.max(best, dist+curr);
            }
        }
        for(int i=z-1; i>=0; i-=2){
            char ch = input.charAt(y);
            int dir = 1; if(x==1) dir = -1;
            int dist = 0;
            int x1;
            if(ch=='T'){
                dist += dir;
                x1 = x;
            }
            else{
                dir = -dir;
                x1 = 1-x;
            }
            int curr = countA1(x1, y+1, i);
            if(-105<=curr && curr<=105) best = Math.max(best, dist+curr);
        }
        X[x][y][z] = 1;
        if(-105<=best && best<=105) A[x][y][z] = best;
        else A[x][y][z] = Integer.MAX_VALUE;
        return A[x][y][z];
    }

    static int countA(int x, int y, int z) {
        if(X[x][y][z]>0) return A[x][y][z];
        if(y>=input.length() && z!=0) return Integer.MAX_VALUE;
        if(y>=input.length()) return 0;
        int dir = 1;
        if(x==1) dir = -1;
        if(z==0){
            int dist = 0;
            char ch;
            for(int i=y; i<input.length(); i++){
                ch = input.charAt(i);
                if(ch=='T') dir = -dir;
                else dist += dir;
            }
            X[x][y][z] = 1;
            A[x][y][z] = dist;
            return dist;
        }
        char ch = input.charAt(y);
        int dist = 0, changed = 0;
        if(ch!='T') dist++;
        else{
            changed = 1;
            dir = -dir;
        }
        if(dir<0) dist = -dist;
        int beforeChange;
        int num = countA(x, y+1, z);
        beforeChange = dist+num;
        int curr;
        int best = beforeChange;
        if(num==Integer.MAX_VALUE) best = Integer.MIN_VALUE;
        for(int i=z; i>=0; i-=2){
            int numb;
            if(changed==0) numb = countA(x, y+1, i);
            else numb = countA(1-x, y+1, i);
            curr = dist+numb;
            if(numb!=Integer.MAX_VALUE && numb!=Integer.MIN_VALUE) best = Math.max(best, curr);
        }
        for(int i=z-1; i>=1; i-=2){
            int numb;
            if(changed==1) numb = countA(x, y+1, i);
            else numb = countA(1-x, y+1, i);
            curr = 1-dist+numb;
            if(numb!=Integer.MAX_VALUE && numb!=Integer.MIN_VALUE) best = Math.max(best, curr);
        }
        X[x][y][z] = 1;
        if(-105<=best && best<=105) A[x][y][z] = best;
        else A[x][y][z] = Integer.MAX_VALUE;
        return A[x][y][z];
    }

    static int countB(int x, int y, int z) {
        if(Y[x][y][z]>0) return B[x][y][z];
        if(y>=input.length() && z!=0) return Integer.MAX_VALUE;
        if(y>=input.length()) return 0;
        int dir = 1;
        if(x==0) dir = -1;
        if(z==0){
            int dist = 0;
            char ch;
            for(int i=y; i<input.length(); i++){
                ch = input.charAt(i);
                if(ch=='T') dir = -dir;
                else dist += dir;
            }
            X[x][y][z] = 1;
            A[x][y][z] = dist;
            return dist;
        }
        char ch = input.charAt(y);
        int dist = 0, changed = 0;
        if(ch!='T') dist++;
        else{
            dir = -dir;
            changed = 1;
        }
        int beforeChange;
        if(dir<0) dist = -dist;
        int numb = countA(x, y+1, z);
        beforeChange = dist+numb;
        int curr;
        int best = beforeChange;
        if(numb==Integer.MAX_VALUE && numb!=Integer.MIN_VALUE) best = Integer.MIN_VALUE;
        for(int i=z; i>=0; i-=2){
            int numb1;
            if(changed==0) numb1 = countB(x, y+1, i);
            else numb1 = countB(1-x, y+1, i);
            curr = dist+numb1;
            if(numb1!=Integer.MAX_VALUE && numb1!=Integer.MIN_VALUE) best = Math.max(best, curr);
        }
        for(int i=z-1; i>=1; i-=2){
            int num;
            if(changed==1) num = countB(x, y+1, i);
            else num = countB(1-x, y+1, i);
            curr = 1-dist+num;
            if(num!=Integer.MAX_VALUE) best = Math.max(best, curr);
        }
        B[x][y][z] = best;
        Y[x][y][z] = 1;
        if(best!=Integer.MIN_VALUE) return best;
        return Integer.MAX_VALUE;
    }
    //FFFTFFF

    static String input;

    static int[][][] A = new int[2][101][51], B = new int[2][101][51],
            X = new int[2][101][51], Y = new int[2][101][51];

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class LogoTurtle {
	static char[] arr;
	static Integer[][][][] dp = new Integer[102][52][202][2];
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
		String s=r.readLine();
		arr=s.toCharArray();
//		System.out.println(arr.length);
		int n=new Integer(r.readLine());
		System.out.println(solve(0,n,0,0));
	}
	// dir = 0 forward
	public static int solve(int index,int rem,int pos,int dir){
		if(rem<0)return -100000;
//		if(pos<0)return -100000;
		if(index==arr.length){
			if(rem==0)
			return Math.abs(pos);
			else return -100000;
		}
		if(dp[index][rem][pos+100][dir]!=null)return dp[index][rem][pos+100][dir];
		if(arr[index]=='F'){
			int max=-1;
			if(dir==0){
				for(int j=0;j<=rem;j++){
					if(j%2==0){
						max=Math.max(max, solve(index+1,rem-j,pos+1,dir));
					}
					else{
						max=Math.max(max, solve(index+1,rem-j,pos,1));
					}
				}
			}
			else{
				for(int j=0;j<=rem;j++){
					if(j%2==0){
						max=Math.max(max,solve(index+1,rem-j,pos-1,1));
					}
					else{
						max=Math.max(max, solve(index+1,rem-j,pos,0));
					}
				}
			}
			return dp[index][rem][pos+100][dir]=max;
		}
		else{
			int max=-1;
			if(dir==0){
				for(int j=0;j<=rem;j++){
					if(j%2==0){
						max=Math.max(max,solve(index+1,rem-j,pos,1));
					}
					else{
						max=Math.max(max, solve(index+1,rem-j,pos+1,0));
					}
				}
			}
			else{
				for(int j=0;j<=rem;j++){
					if(j%2==0){
						max=Math.max(max,solve(index+1,rem-j,pos,0));
					}
					else{
						max=Math.max(max, solve(index+1,rem-j,pos-1,1));
					}
				}
			}
			return dp[index][rem][pos+100][dir]=max;
		}

	}
}

import java.util.*;
import java.io.*;
public class Main {
    static char[] arr;
    static int n;
    static int l;
    static int [][][] dp;
    static int [][][] dpp;
    public static int solve(int i, int j,int f){
        if(i>=l){ if((n-j)%2==0)return 0;
            else return -1;
        }
        if(j>n) return -100000;
        if(dp[i][j][f]!=-1) return dp[i][j][f];

        if(f==0){
            if(arr[i]=='F'){
            return dp[i][j][f]= Math.max(1+solve(i+1,j,f), solve(i+1,j+1,1-f));

            }else{
            return dp[i][j][f]= Math.max(solve(i+1,j,1-f),1+solve(i+1,j+1,f));

            }
        }
        else{
           if(arr[i]=='F'){
            return dp[i][j][f]= Math.max(-1+solve(i+1,j,f),solve(i+1,j+1,1-f));

            }else{
            return dp[i][j][f]= Math.max(solve(i+1,j,1-f),-1+ solve(i+1,j+1,f));
            }
        }
    }
     public static int solve2(int i, int j,int f){
        if(i>=l){ if((n-j)%2==0)return 0;
            else return 1;
        }
        if(j>n) return 100000;
        if(dpp[i][j][f]!=-1) return dpp[i][j][f];

       if(f==0){
            if(arr[i]=='F'){
            return dpp[i][j][f]= Math.min(1+solve2(i+1,j,f), solve2(i+1,j+1,1-f));

            }else{
            return dpp[i][j][f]= Math.min(solve2(i+1,j,1-f),1+solve2(i+1,j+1,f));

            }
        }
        else{
           if(arr[i]=='F'){
            return dpp[i][j][f]= Math.min(-1+solve2(i+1,j,f),solve2(i+1,j+1,1-f));

            }else{
            return dpp[i][j][f]= Math.min(solve2(i+1,j,1-f),-1+ solve2(i+1,j+1,f));
            }
        }

     }
  public static void main(String[] args) throws IOException,InterruptedException{
	BufferedReader	 br = new BufferedReader(new InputStreamReader(System.in));
	PrintWriter out = new PrintWriter(System.out);
     	// String s = br.readLine();
        // char[] arr=s.toCharArray();
        // ArrayList<Integer> arrl = new ArrayList<Integer>();
        // TreeSet<Integer> ts1 = new TreeSet<Integer>();
        // HashSet<Integer> h = new HashSet<Integer>();
        // HashMap<Integer, Integer> map= new HashMap<>();
        // PriorityQueue<String> pQueue = new PriorityQueue<String>();
        // LinkedList<String> object = new LinkedList<String>();
        // StringBuilder str = new StringBuilder();
         String s = br.readLine();
         arr=s.toCharArray();
         l = arr.length;
 	    StringTokenizer   st = new StringTokenizer(br.readLine());
 	       n = Integer.parseInt(st.nextToken());
 	       dp = new int [105][105][2];
 	       for(int i =0; i<105; i++){
 	           for(int j=0; j<105; j++)
 	           Arrays.fill(dp[i][j],-1);
 	       }
 	       int ans = solve(0,0,0);
 	       dpp = new int [105][105][2];
 	       for(int i =0; i<105; i++){
 	           for(int j=0; j<105; j++)
 	           Arrays.fill(dpp[i][j],-1);
 	       }
 	       int ans2 = solve2(0,0,0);
 	       int max = Math.max(ans,Math.abs(ans2));
 	       out.println(max);

 	  out.flush();

	}}

import java.util.*;
public class Code {
	static int[][][] dp = new int[105][105][320];
	public static int f(int i,int x,int vx,int c,char[] s) {
		if(c==0 && i<s.length) {
			return f(i+1,(s[i]=='F')?x+vx:x,(s[i]=='F')?vx:-vx,c,s);
		}
		if(i==s.length) {
			if(c==0) {
				//System.out.println(x + " " +Arrays.toString(s));
				return Math.abs(x);
			}
			return -1;
		}
		if(dp[i][c][x+105]!=-1)return dp[i][c][(x+105)];
		int b =0;
		if(s[i]=='F' && c>0) {
			char[] st = s.clone();
			st[i]='T';
			b = Math.max(f(i,x,vx,c-1,st),f(i+1,x+vx,vx,c,s));
		}else if(c>0){
			char[]st = s.clone();
			st[i]='F';
			b = Math.max(f(i,x,vx,c-1,st),f(i+1,x,-vx,c,s));
		}
		return dp[i][c][(x+105)] = b;
	}

	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		char[]st = s.toCharArray();
		int n = sc.nextInt();

		for(int i=0;i<dp.length;i++)
			for(int j=0;j<dp[i].length;j++)
				for(int k=0;k<dp[i][j].length;k++)
					dp[i][j][k]=-1;
		System.out.println(f(0,0,1,n,st));
		//System.out.println(Arrays.deepToString(dp));
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class Solveaproblem {
    private static int MIN = -200000;
    private static int MAX = 200000;
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        char[] arr = reader.readLine().toCharArray();
        int m = arr.length;
        int n = Integer.parseInt(reader.readLine());
        int[][][] min = new int[m+1][n+1][2];
        int[][][] max = new int[m+1][n+1][2];
        for (int i=0; i<=m; i++) {
            for (int j=0; j<=n; j++) {
                for (int k=0; k<2; k++) {
                    min[i][j][k] = MAX;
                    max[i][j][k] = MIN;
                }
            }
        }
        min[0][0][0] = 0; max[0][0][0] = 0;
        for (int i=1; i<=m; i++) {
            if (arr[i-1]=='F') {
                min[i][0][0] = min[i-1][0][0] + 1;
                min[i][0][1] = min[i-1][0][1] - 1;
                max[i][0][0] = max[i-1][0][0] + 1;
                max[i][0][1] = max[i-1][0][1] - 1;
            } else {
                min[i][0][0] = min[i-1][0][1];
                min[i][0][1] = min[i-1][0][0];
                max[i][0][0] = max[i-1][0][1];
                max[i][0][1] = max[i-1][0][0];
            }
            if (min[i][0][0]==MAX+1) min[i][0][0] = MAX;
            if (min[i][0][1]==MAX-1) min[i][0][1] = MAX;
            if (max[i][0][0]==MIN+1) max[i][0][0] = MIN;
            if (max[i][0][1]==MIN-1) max[i][0][1] = MIN;
            for (int j=1; j<=n; j++) {
                if (arr[i-1]=='F') {
                    min[i][j][0] = Math.min(min[i-1][j][0] + 1, min[i-1][j-1][1]);
                    min[i][j][1] = Math.min(min[i-1][j][1] - 1, min[i-1][j-1][0]);
                    max[i][j][0] = Math.max(max[i-1][j][0] + 1, max[i-1][j-1][1]);
                    max[i][j][1] = Math.max(max[i-1][j][1] - 1, max[i-1][j-1][0]);
                } else {
                    min[i][j][0] = Math.min(min[i-1][j][1], min[i-1][j-1][0] + 1);
                    min[i][j][1] = Math.min(min[i-1][j][0], min[i-1][j-1][1] - 1);
                    max[i][j][0] = Math.max(max[i-1][j][1], max[i-1][j-1][0] + 1);
                    max[i][j][1] = Math.max(max[i-1][j][0], max[i-1][j-1][1] - 1);
                }
                if (min[i][j][0]==MAX+1) min[i][j][0] = MAX;
                if (min[i][j][1]==MAX-1) min[i][j][1] = MAX;
                if (max[i][j][0]==MIN+1) max[i][j][0] = MIN;
                if (max[i][j][1]==MIN-1) max[i][j][1] = MIN;
            }
        }
        int minimum = MAX, maximum = MIN;
        for (int j=n%2; j<=n; j+=2) {
            for (int k=0; k<2; k++) {
                minimum = Math.min(minimum, min[m][j][k]);
                maximum = Math.max(maximum, max[m][j][k]);
            }
        }
        PrintWriter writer = new PrintWriter(System.out);
        writer.print(Math.max(Math.abs(minimum), Math.abs(maximum)));
        writer.close();
    }
}

import java.util.Scanner;

public class CF133E {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String commands = sc.next();
        int n = sc.nextInt();

        State[][][][] dp = new State[commands.length()+1][n+1][201][2];
        State init = State.valueOf(0);
        dp[0][0][100][0] = init;
        for (int i = 1; i < dp.length; i++) {
            boolean commandIsT = commands.charAt(i-1) == 'T';
            for (int j = 0; j < n+1; j++) {
                for (int k = 0; k <= 200; k++) {
                    for (int l = 0; l < 2; l++) {
                        State temp;
                        int dx = l == 0 ? -1 : 1;
                        if (commandIsT) {
                            if(dp[i-1][j][k][l] != null) {
                                temp = State.getBigger(dp[i-1][j][k][l], dp[i][j][k][(l+1)%2]);
                                dp[i][j][k][(l+1)%2] = temp;
                            }
                            if(j > 0 && dp[i-1][j-1][k][l] != null) {
                                temp = State.getBigger(dp[i-1][j-1][k][l].forward(dx), dp[i][j][k+dx][l]);
                                dp[i][j][k+dx][l] = temp;
                            }
                        }
                        else {
                            if(dp[i-1][j][k][l] != null) {
                                temp = State.getBigger(dp[i-1][j][k][l].forward(dx), dp[i][j][k+dx][l]);
                                dp[i][j][k+dx][l] = temp;
                            }
                            if(j > 0 && dp[i-1][j-1][k][l] != null) {
                                temp = State.getBigger(dp[i-1][j-1][k][l], dp[i][j][k][(l+1)%2]);
                                dp[i][j][k][(l+1)%2] = temp;
                            }
                        }
                        if(j > 1) dp[i][j][k][l] = State.getBigger(dp[i][j-2][k][l], dp[i][j][k][l]);
                    }
                }
            }
        }
        int max = 0;
        for (int i = 0; i <= 200; i++) {
            for (int j = 0; j < 2; j++) {
                if(dp[commands.length()][n][i][j] != null)
                    max = Math.max(max, dp[commands.length()][n][i][j].dist());
            }
        }
        System.out.println(max);
    }

    static class State {
        final int x;
        public State(int x) {
            this.x = x;
        }
        static State valueOf(int x) {
            return new State(x);
        }
        State forward(int dx) {
            return valueOf(x + dx);
        }
        int dist() {
            return Math.abs(x);
        }

        static State getBigger(State a, State b) {
            if (a == null) return b;
            if (b == null) return a;
            return a.dist() > b.dist() ? a : b;
        }

    }

}

import java.io.Closeable;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.AbstractList;
import java.io.Writer;
import java.util.Collection;
import java.util.List;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Jacob Jiang
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		QuickScanner in = new QuickScanner(inputStream);
		ExtendedPrintWriter out = new ExtendedPrintWriter(outputStream);
		TaskC solver = new TaskC();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskC {
    public static final int INF = Integer.MAX_VALUE / 20;

	public void solve(int testNumber, QuickScanner in, ExtendedPrintWriter out) {
        char[] commands = (" " + in.next()).toCharArray();
        int n = commands.length - 1;
        int toChange = in.nextInt();
        int[][][] minPosition = new int[n + 1][toChange + 1][2];
        int[][][] maxPosition = new int[n + 1][toChange + 1][2];
        ArrayUtils.fill(minPosition, INF);
        ArrayUtils.fill(maxPosition, -INF);
        Arrays.fill(minPosition[0][0], 0);
        Arrays.fill(maxPosition[0][0], 0);
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= toChange; j++) {
                for (int k = 0; k < 2; k++) {
                    //not change
                    if (commands[i] == 'T') {
                        minPosition[i][j][k] = Math.min(minPosition[i][j][k], minPosition[i - 1][j][1 - k]);
                        maxPosition[i][j][k] = Math.max(maxPosition[i][j][k], maxPosition[i - 1][j][1 - k]);
                    } else {
                        minPosition[i][j][k] = Math.min(minPosition[i][j][k], minPosition[i - 1][j][k] + toward(k));
                        maxPosition[i][j][k] = Math.max(maxPosition[i][j][k], maxPosition[i - 1][j][k] + toward(k));
                    }
                    //change
                    if (j > 0) {
                        if (commands[i] == 'T') {
                            minPosition[i][j][k] = Math.min(minPosition[i][j][k], minPosition[i - 1][j - 1][k] + toward(k));
                            maxPosition[i][j][k] = Math.max(maxPosition[i][j][k], maxPosition[i - 1][j - 1][k] + toward(k));
                        } else {
                            minPosition[i][j][k] = Math.min(minPosition[i][j][k], minPosition[i - 1][j - 1][1 - k]);
                            maxPosition[i][j][k] = Math.max(maxPosition[i][j][k], maxPosition[i - 1][j - 1][1 - k]);
                        }
                    }
                }
            }
        }
        int answer = 0;
        for (int j = toChange % 2; j <= toChange; j += 2) {
            for (int k = 0; k < 2; k++) {
                answer = Math.max(answer, -minPosition[n][j][k]);
                answer = Math.max(answer, maxPosition[n][j][k]);
            }
        }
        out.println(answer);

    }

    private int toward(int x) {
        return x == 0 ? 1 : -1;
    }
}

class QuickScanner implements Iterator<String>, Closeable {
    BufferedReader reader;
    StringTokenizer tokenizer;
    boolean endOfFile = false;

    public QuickScanner(InputStream inputStream) {
        reader = new BufferedReader(new InputStreamReader(inputStream));
        tokenizer = null;
    }

    public boolean hasNext() {
        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                checkNext();
            } catch (NoSuchElementException ignored) {
            }

        }
        return !endOfFile;
    }

    private void checkNext() {
        if (endOfFile) {
            throw new NoSuchElementException();
        }
        try {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                tokenizer = new StringTokenizer(reader.readLine());
            }
        } catch (Exception e) {
            endOfFile = true;
            throw new NoSuchElementException();
        }
    }

    public String next() {
        checkNext();
        return tokenizer.nextToken();
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }

    public int nextInt() {
        return Integer.parseInt(next());
    }

    public void close() {
        try {
            reader.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

class ExtendedPrintWriter extends PrintWriter {

    public ExtendedPrintWriter(Writer out) {
        super(out);
    }

    public ExtendedPrintWriter(OutputStream out) {
        super(out);
    }

    }

class ArrayUtils {

    private ArrayUtils() {
    }

    public static void fill(int[][] array, int val) {
        for (int[] subArray : array) {
            Arrays.fill(subArray, val);
        }
    }

    public static void fill(int[][][] array, int val) {
        for (int[][] subArray : array) {
            ArrayUtils.fill(subArray, val);
        }
    }

    }

import java.io.* ;
import java.util.*;

import static java.lang.Math.* ;
import static java.util.Arrays.* ;

public class C {

	public static void main(String[] args) throws IOException {

		new C().solveProblem();

		out.close();
	}

	static Scanner in = new Scanner(new InputStreamReader(System.in));
	//static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	static PrintStream out = new PrintStream(new BufferedOutputStream(System.out));

	char[] c ;
	int n ;
	public void solveProblem() {

		c = in.nextLine().toCharArray() ;
		n = c.length ;
		int a = in.nextInt() ;

		out.println(solv( 0, 0, 1, a)) ;
	}

	HashMap<String,Integer> map = new HashMap<String, Integer>() ;

	private int solv(int i, int plaats, int richting, int nog) {

		if( nog < 0 )
			return 0 ;

		String s=  i + "|" + plaats + "|" + richting + "|" + nog ;
		if( map.containsKey(s))
			return map.get(s) ;

		if( i == n ){
			if( nog % 2 == 0)
				return abs(plaats) ;
			else
				return 0 ;
		}

		int beste = 0 ;

		if( c[i] == 'F'){
			beste = max(beste,solv(i+1,plaats+richting,richting,nog)) ;
			beste = max(beste,solv(i+1,plaats,-richting,nog-1)) ;
		}else{
			beste = max(beste,solv(i+1,plaats+richting,richting,nog-1)) ;
			beste = max(beste,solv(i+1,plaats,-richting,nog)) ;
		}

		map.put(s, beste) ;
		return beste ;

	}

}

import java.util.*;
public class C {
	static int [] reverse = new int [257];
	static int [][][] dp = new int [105][105][2];
	static char [] path;
	static int MIN_VAL = -(1<<20);
	public static void main (String [] arg) {
		Scanner sc = new Scanner(System.in);
		path = sc.next().toCharArray();
		int n = sc.nextInt();

		for (int i = 0; i<dp.length; ++i) for (int j = 0; j<dp[0].length; ++j) Arrays.fill(dp[i][j], MIN_VAL);
		int ans = recurse(n, 0, 1);
		for (int i = 0; i<dp.length; ++i) for (int j = 0; j<dp[0].length; ++j) Arrays.fill(dp[i][j], MIN_VAL);
		int ans2=recurse(n,0,0);
		System.out.println(Math.max(ans,ans2));
	}
	public static int recurse(int n, int pos, int orientation) {
		//System.err.println("@ " + n + " , " + pos + " , " + orientation);
		if (dp[n][pos][orientation] > MIN_VAL) return dp[n][pos][orientation];
		if (pos >= path.length) return ( n%2 == 0) ? 0 : MIN_VAL;
		int dir = (orientation == 0) ? -1 : 1;

		int best = MIN_VAL;
		if (n != 0) {
			if (path[pos] == 'F') best = Math.max(best, recurse(n-1, pos+1, 1-orientation));
			if (path[pos] == 'T') best = Math.max(best, dir + recurse(n-1, pos+1, orientation));
		}
		if (path[pos] == 'T') best = Math.max(best, recurse(n, pos+1, 1-orientation));
		if (path[pos] == 'F') best = Math.max(best, dir + recurse(n, pos+1, orientation));
		dp[n][pos][orientation] = best;
		return best;
	}

}

import java.util.Arrays;
import java.util.Scanner;
import static java.lang.Math.*;

public class turtle {
    public static void debug(Object... obs) {
        System.out.println(Arrays.deepToString(obs));
    }

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);

        String s = sc.next();
        int k = sc.nextInt();
        int n = s.length();

        int[][][] dp = new int[n + 1][k + 1][2];
        int[]signum=new int[n];
        int si=1;
        for(int i=0;i<s.length();i++)
        {
            if(s.charAt(i)=='T') si*=-1;
            signum[i]=si;
        }

        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= k; j++) {
                dp[i][j][0] = Integer.MIN_VALUE;
                dp[i][j][1] = Integer.MAX_VALUE;
            }
        }

        dp[0][0][0] = 0;
        dp[0][0][1] = 0;

        for (int i = 1; i <= n; i++) {
            int trn = 0;
            int inc = 1;
            if (s.charAt(i - 1) == 'T') {
                trn = 1;
            }
            for (int j = 0; j <= k; j++) {
                for (int f = 0; f <= j; f++) {
                    int d = (j - f + trn) % 2;
                    int sgn = 1;
                    if (i > 1) {
                        sgn = (signum[i-2]==-1) ? ((f % 2 == 0) ? -1 : 1)
                                : ((f % 2 == 0) ? 1 : -1);
                    }

                    //debug(i, j, f, d, sgn);

                    if(dp[i - 1][f][1] == Integer.MAX_VALUE || dp[i - 1][f][0] == Integer.MIN_VALUE) continue;

                    dp[i][j][0] = Math.max(dp[i][j][0], dp[i - 1][f][0] + sgn
                            * (1 - d) * inc);
                    dp[i][j][0] = Math.max(dp[i][j][0], dp[i - 1][f][1] + sgn
                            * (1 - d) * inc);
                    dp[i][j][1] = Math.min(dp[i][j][1], dp[i - 1][f][0] + sgn
                            * (1 - d) * inc);
                    dp[i][j][1] = Math.min(dp[i][j][1], dp[i - 1][f][1] + sgn
                            * (1 - d) * inc);
                }
            }
        }

        int ma = Integer.MIN_VALUE;
        for (int j = 0; j < 2; j++)
            if (dp[n][k][j] != Integer.MAX_VALUE
                    && dp[n][k][j] != Integer.MIN_VALUE)
                ma = Math.max(ma, Math.abs(dp[n][k][j]));
        System.out.println(ma);
    }
}

import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class Main{
    public static void main(String[]args){
        InputStream in = System.in;
        PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
        try{
//          in = new BufferedInputStream(new FileInputStream(new File("input.txt")));
//          out = new PrintWriter(new BufferedOutputStream(new FileOutputStream("output.txt")));
        }catch (Exception e) {
        }
        new Main().run(in,out);
        out.flush();
    }
    private void debug(Object...os){
        System.err.println(deepToString(os));
    }

    private void run(InputStream in,PrintWriter out){
        char[]cs = next(in).toCharArray();
        int m=nextInt(in);
        int n=cs.length;
        int off = n+5;
        boolean[][][] dp=new boolean[2][n*2+10][m+1];// step,dist,used
        dp[0][off][0]=true;
        int cur=0,nxt=1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n*2+10; j++) {
                fill(dp[nxt][j],false);
            }
            for (int j = 0; j < n*2+10; j++) {
                for (int k = 0; k <= m; k++) {
                    if(dp[cur][j][k]){
                        // change
                        boolean turn = cs[i]=='F';
                        int add = 1;
                        if(k+add<=m)dp[nxt][turn?off-(j-off) : j+1][k+add] = true;
                        // as is
                        turn = cs[i]=='T';
                        add=0;
                        if(k+add<=m)dp[nxt][turn?off-(j-off) : j+1][k+add] = true;
                    }
                }
            }
            int tmp=cur;cur=nxt;nxt=tmp;
        }
        int res = 0;
        for (int i = 0; i < n*2+10; i++) {
            for(int j=0;j<=m;j++)if((m-j)%2==0)
            if(dp[cur][i][j])res = max(res,abs(off-i));

//          if(dp[cur][i][m])res = max(res,abs(off-i));
        }
        out.println(res);
    }

    private String next(InputStream in) {
        try {
            StringBuilder res = new StringBuilder("");
            int c = in.read();
            while (Character.isWhitespace(c))
                c = in.read();
            do {
                res.append((char) c);
            } while (!Character.isWhitespace(c = in.read()));
            return res.toString();
        } catch (Exception e) {
            return null;
        }
    }

    private int nextInt(InputStream in){
        try{
            int c=in.read();
            if(c==-1) return c;
            while(c!='-'&&(c<'0'||'9'<c)){
                c=in.read();
                if(c==-1) return c;
            }
            if(c=='-') return -nextInt(in);
            int res=0;
            do{
                res*=10;
                res+=c-'0';
                c=in.read();
            }while('0'<=c&&c<='9');
            return res;
        }catch(Exception e){
            return -1;
        }
    }

    private long nextLong(InputStream in){
        try{
            int c=in.read();
            if(c==-1) return c;
            while(c!='-'&&(c<'0'||'9'<c)){
                c=in.read();
                if(c==-1) return c;
            }
            if(c=='-') return -nextLong(in);
            long res=0;
            do{
                res*=10;
                res+=c-'0';
                c=in.read();
            }while('0'<=c&&c<='9');
            return res;
        }catch(Exception e){
            return -1;
        }
    }
}

import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.OutputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Alex
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        int IMPOSSIBLE = 1111111;
        int n;
        int[][][][] mem;
        boolean[] forward;

        int maxdp(int index, boolean right, int distance, int flips) {
            if(index == forward.length) {
                if(flips == 0) return distance;
                return -1000;
            }
            if(mem[index][right ? 1 : 0][distance + n + 1][flips] != IMPOSSIBLE)
                return mem[index][right ? 1 : 0][distance + n + 1][flips];
            int res = 0;
            for(int flipped = 0; flipped <= flips; flipped++) {
                int change = flipped % 2;
                boolean goforward = forward[index];
                if(change == 1) goforward = !goforward;
                if(goforward) {
                    int newdistance = distance;
                    if(right) newdistance++;
                    else newdistance--;
                    res = Math.max(res, maxdp(index + 1, right, newdistance, flips - flipped));
                } else {
                    res = Math.max(res, maxdp(index + 1, !right, distance, flips - flipped));
                }
            }
            return mem[index][right ? 1 : 0][distance + n + 1][flips] = res;
        }

        int mindp(int index, boolean right, int distance, int flips) {
            if(index == forward.length) {
                if(flips == 0) return distance;
                return 1000;
            }
            if(mem[index][right ? 1 : 0][distance + n + 1][flips] != IMPOSSIBLE)
                return mem[index][right ? 1 : 0][distance + n + 1][flips];
            int res = 1000;
            for(int flipped = 0; flipped <= flips; flipped++) {
                int change = flipped % 2;
                boolean goforward = forward[index];
                if(change == 1) goforward = !goforward;
                if(goforward) {
                    int newdistance = distance;
                    if(right) newdistance++;
                    else newdistance--;
                    res = Math.min(res, mindp(index + 1, right, newdistance, flips - flipped));
                } else {
                    res = Math.min(res, mindp(index + 1, !right, distance, flips - flipped));
                }
            }
            return mem[index][right ? 1 : 0][distance + n + 1][flips] = res;
        }

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            char[] input = in.next().toCharArray();
            forward = new boolean[input.length];
            n = forward.length;
            for(int i = 0; i < input.length; i++) if(input[i] == 'F') forward[i] = true;
            int flips = in.readInt();
            mem = new int[n + 1][2][2 * n + 2][flips + 1];
            ArrayUtils.fill(mem, IMPOSSIBLE);
            int maxres = maxdp(0, true, 0, flips);
            ArrayUtils.fill(mem, IMPOSSIBLE);
            int minres = mindp(0, true, 0, flips);
            out.printLine(Math.max(maxres, Math.abs(minres)));
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void printLine(int i) {
            writer.println(i);
        }

    }

    static class ArrayUtils {
        public static void fill(int[][] array, int value) {
            for(int[] row : array)
                Arrays.fill(row, value);
        }

        public static void fill(int[][][] array, int value) {
            for(int[][] subArray : array)
                fill(subArray, value);
        }

        public static void fill(int[][][][] array, int value) {
            for(int[][][] subArray : array)
                fill(subArray, value);
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if(numChars == -1)
                throw new InputMismatchException();
            if(curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch(IOException e) {
                    throw new InputMismatchException();
                }
                if(numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while(isSpaceChar(c))
                c = read();
            int sgn = 1;
            if(c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if(c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while(!isSpaceChar(c));
            return res * sgn;
        }

        public String readString() {
            int c = read();
            while(isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                if(Character.isValidCodePoint(c))
                    res.appendCodePoint(c);
                c = read();
            } while(!isSpaceChar(c));
            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if(filter != null)
                return filter.isSpaceChar(c);
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next() {
            return readString();
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class G {
	static int table[][][][] = new int[201][101][51][2];
	static int comm[];

	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(
				(System.in)));
		String s = in.readLine();
		int m = s.length();
		comm = new int[m];
		for (int i = 0; i < m; i++) {
			if (s.charAt(i) == 'F')
				comm[i] = 1;
			else
				comm[i] = 0;
		}
		int n = Integer.parseInt(in.readLine());

		for (int i = 0; i < table.length; i++) {
			for (int j = 0; j < table[i].length; j++) {
				for (int j2 = 0; j2 < table[i][j].length; j2++) {
					Arrays.fill(table[i][j][j2], -1);
				}
			}
		}

		System.out.println(dp(100, 0, n, 1));
	}

	static int dp(int p, int i, int k, int d) {
		if (table[p][i][k][d] != -1)
			return table[p][i][k][d];
		if (i == comm.length) {
			int s = 0;
			if (k == 0)
				s = Math.abs(p - 100);
			else
				s = -1;
			return table[p][i][k][d] = s;
		}
		int s = dp(m(p, i, d, false), i + 1, k, dir(p, i, d, false));
		if (k > 0) {
			s = Math.max(s,
					dp(m(p, i, d, true), i + 1, k - 1, dir(p, i, d, true)));
		}
		if (k > 1) {
			s = Math.max(s, dp(p, i, k - 2, d));
		}
		return table[p][i][k][d] = s;
	}

	static int m(int p, int i, int d, boolean b) {
		if ((comm[i] == 1 && !b) || (comm[i] == 0 && b))
			return p += (d == 1 ? 1 : -1);
		return p;
	}

	static int dir(int p, int i, int d, boolean b) {
		if ((comm[i] == 0 && !b) || (comm[i] == 1 && b))
			return 1 - d;
		return d;
	}
}

import java.io.*;
import java.util.*;

public class E {

    boolean DP[][][][];

    public boolean contains_printing_char(String s) {
	for (int i=0; i<s.length(); i++) {
	    if (s.charAt(i) == 'H' || s.charAt(i) =='Q' || s.charAt(i) =='9') return true;
	}
	return false;
    }

    public void read_input_and_solve() throws IOException {
	Scanner sc = new Scanner(System.in);
	String p = sc.nextLine();
	int changes = sc.nextInt();
	int n = p.length();
	DP = new boolean[n+1][2*n+1][changes+1][2];
	DP[0][n][0][0] = true;
	for (int t=1; t<=n; t++) {
	    char ch = p.charAt(t-1);
	    for (int h=0; h<=2*n; h++) {
		for (int c=0; c<=changes; c++) {
		    for (int dir=0; dir<2; dir++) {
			/* assign DP[t][h][c][dir] */
			boolean ans = false;
			int cc;
			if (ch=='T') cc=c; else cc=c-1;
			if (cc>=0) ans = ans || (DP[t-1][h][cc][1-dir]);

			if (ch=='F') cc=c; else cc=c-1;
			int ph = h + 1 - 2*dir;
			if (cc>=0 && ph>=0 && ph<=2*n) ans = ans || (DP[t-1][ph][cc][dir]);
			DP[t][h][c][dir] = ans;
			/*
			System.out.printf("DP[%d][%d][%d][%d] = %B\n", t, h, c, dir, ans);
			*/
		    }
		}
	    }
	}
	int maxd = 0;
	for (int h=0; h<=2*n; h++) {
	    for (int c=changes&1; c<=changes; c+=2) {
		for (int dir=0; dir<2; dir++) {
		    if (DP[n][h][c][dir]) maxd = Math.max(maxd, (Math.abs(h-n)));
		}
	    }
	}
	System.out.println(maxd);
    }

    public static void main(String[] args) throws IOException {
	(new E()).read_input_and_solve();
    }
}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

public class _132C {

  static final int OFFSET = 50;
  static int n;
  static int m;
  static char[] a;
  static Set<Integer>[][][] f;

  @SuppressWarnings("unchecked")
  public static void main(String[] args) throws Exception {
    Reader.init(System.in);
    BufferedWriter cout = new BufferedWriter(new OutputStreamWriter(System.out));

    a = Reader.next().toCharArray();
    n = a.length;
    a = (" " + String.valueOf(a)).toCharArray();
    m = Reader.nextInt();
    f = new HashSet[n + 1][m + 1][2];

    for (int i = 0; i < f.length; i++)
      for (int j = 0; j < f[i].length; j++)
        for (int k = 0; k < f[i][j].length; k++)
          f[i][j][k] = new HashSet<>();

    f[0][0][1].add(0);
    for (int i = 0; i < n; i++)
      for (int j = 0; j <= m; j++)
        for (int k = 0; k < 2; k++) {
          if (a[i + 1] == 'T') {
            for (int pos : f[i][j][k]) {
              f[i + 1][j][1 - k].add(pos);
              if (j < m)
                f[i + 1][j + 1][k].add(pos + (k == 1 ? 1 : -1));
            }
          } else {
            for (int pos : f[i][j][k]) {
              f[i + 1][j][k].add(pos + (k == 1 ? 1 : -1));
              if (j < m)
                f[i + 1][j + 1][1 - k].add(pos);
            }
          }
        }

    int ans = 0;
    for (int j = m; j >= 0; j -= 2)
      for (int dir = 0; dir < 2; dir++)
        for (int pos : f[n][j][dir])
          ans = Math.max(ans, Math.abs(pos));
    System.out.println(ans);
    cout.close();
  }

  static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
    final U _1;
    final V _2;

    private Pair(U key, V val) {
      this._1 = key;
      this._2 = val;
    }

    public static <U extends Comparable<U>, V extends Comparable<V>> Pair<U, V> instanceOf(U _1, V _2) {
      return new Pair<U, V>(_1, _2);
    }

    @Override
    public String toString() {
      return _1 + " " + _2;
    }

    @Override
    public int hashCode() {
      int res = 17;
      res = res * 31 + _1.hashCode();
      res = res * 31 + _2.hashCode();
      return res;
    }

    @Override
    public int compareTo(Pair<U, V> that) {
      int res = this._1.compareTo(that._1);
      if (res < 0 || res > 0)
        return res;
      else
        return this._2.compareTo(that._2);
    }

    @Override
    public boolean equals(Object obj) {
      if (this == obj)
        return true;
      if (!(obj instanceof Pair))
        return false;
      Pair<?, ?> that = (Pair<?, ?>) obj;
      return _1.equals(that._1) && _2.equals(that._2);
    }
  }

  /** Class for buffered reading int and double values */
  static class Reader {
    static BufferedReader reader;
    static StringTokenizer tokenizer;

    /** call this method to initialize reader for InputStream */
    static void init(InputStream input) {
      reader = new BufferedReader(new InputStreamReader(input));
      tokenizer = new StringTokenizer("");
    }

    /** get next word */
    static String next() throws IOException {
      while (!tokenizer.hasMoreTokens()) {
        // TODO add check for eof if necessary
        tokenizer = new StringTokenizer(reader.readLine());
      }
      return tokenizer.nextToken();
    }

    static int nextInt() throws IOException {
      return Integer.parseInt(next());
    }

    static double nextDouble() throws IOException {
      return Double.parseDouble(next());
    }
  }

  static class ArrayUtil {
    static void swap(int[] a, int i, int j) {
      int tmp = a[i];
      a[i] = a[j];
      a[j] = tmp;
    }

    static void swap(long[] a, int i, int j) {
      long tmp = a[i];
      a[i] = a[j];
      a[j] = tmp;
    }

    static void swap(double[] a, int i, int j) {
      double tmp = a[i];
      a[i] = a[j];
      a[j] = tmp;
    }

    static void swap(char[] a, int i, int j) {
      char tmp = a[i];
      a[i] = a[j];
      a[j] = tmp;
    }

    static void swap(boolean[] a, int i, int j) {
      boolean tmp = a[i];
      a[i] = a[j];
      a[j] = tmp;
    }

    static void reverse(int[] a, int i, int j) {
      for (; i < j; i++, j--)
        swap(a, i, j);
    }

    static void reverse(long[] a, int i, int j) {
      for (; i < j; i++, j--)
        swap(a, i, j);
    }

    static void reverse(double[] a, int i, int j) {
      for (; i < j; i++, j--)
        swap(a, i, j);
    }

    static void reverse(char[] a, int i, int j) {
      for (; i < j; i++, j--)
        swap(a, i, j);
    }

    static void reverse(boolean[] a, int i, int j) {
      for (; i < j; i++, j--)
        swap(a, i, j);
    }

    static long sum(int[] a) {
      int sum = 0;
      for (int i : a)
        sum += i;
      return sum;
    }

    static long sum(long[] a) {
      long sum = 0;
      for (long i : a)
        sum += i;
      return sum;
    }

    static double sum(double[] a) {
      double sum = 0;
      for (double i : a)
        sum += i;
      return sum;
    }

    static int max(int[] a) {
      int max = Integer.MIN_VALUE;
      for (int i : a)
        if (i > max)
          max = i;
      return max;
    }

    static int min(int[] a) {
      int min = Integer.MAX_VALUE;
      for (int i : a)
        if (i < min)
          min = i;
      return min;
    }

    static long max(long[] a) {
      long max = Long.MIN_VALUE;
      for (long i : a)
        if (i > max)
          max = i;
      return max;
    }

    static long min(long[] a) {
      long min = Long.MAX_VALUE;
      for (long i : a)
        if (i < min)
          min = i;
      return min;
    }
  }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class ProblemE {

    public static int NONE = -99999;

    public static String _line;
    public static int _n;

    public static int[][][][] memo;

    public static int dfs(int l, int c, int d, int now) {
        if (c > _n) {
            return NONE;
        }
        if (l == _line.length()) {
            if (c != _n) {
                return NONE;
            }
            return Math.abs(100 - now);
        }

        int dd = (d == -1) ? 0 : 1;
        if (memo[l][c][dd][now] >= 1) {
            return memo[l][c][dd][now];
        }

        int max = NONE;
        boolean isforward = (_line.charAt(l) == 'F');
        for (int change = 0 ; change <= _n ; change++) {
            int val = 0;
            if (change % 2 == 0) {
                if (isforward) {
                    val = dfs(l+1, c+change, d, now+d);
                } else {
                    val = dfs(l+1, c+change, -d, now);
                }
            } else {
                if (isforward) {
                    val = dfs(l+1, c+change, -d, now);
                } else {
                    val = dfs(l+1, c+change, d, now+d);
                }
            }
            max = Math.max(max, val);
        }
        memo[l][c][dd][now] = max;
        return max;
    }

    public static void main(String[] args) throws IOException {
        BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
        _line = s.readLine();
        _n = Integer.valueOf(s.readLine());

        memo = new int[101][51][2][201];

        System.out.println(dfs(0, 0, 1, 100));

    }
}

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    static char[] a;
    public static void main(String[] args) {
        Scanner r = new Scanner(System.in);

        a = r.next().toCharArray();
        int n = r.nextInt();

        for(int[][][][] l: dp)
        for(int[][][] i : l)
        for(int[][] j : i)
        for(int[] k : j)
            Arrays.fill(k, -1);

        int max = go(0, n, 0, 1, 0);

        System.out.println(max);
    }

    static int off = 102;
    static int[][][][][] dp = new int[101][51][210][3][2];
    private static int go(int i, int rem, int pos, int dir, int c) {
        if(i == a.length){
            if(rem == 0)return Math.abs(pos);
            else return 0;
        }
        if(dp[i][rem][pos + off][dir + 1][c] != -1)return dp[i][rem][pos + off][dir + 1][c];

        int w1 = 0, w2 = 0;
        if(!(a[i] == 'F' ^ c == 0)){
            w1 = go(i+1, rem, pos + dir, dir, 0);
            if(rem-1 >= 0)w2 = go(i, rem-1, pos, dir, 1-c);

            return dp[i][rem][pos + off][dir + 1][c] = Math.max(w1, w2);
        }else{
            w1 = go(i+1, rem, pos, -dir, 0);
            if(rem-1 >= 0)w2 = go(i, rem-1, pos, dir, 1-c);

            return dp[i][rem][pos + off][dir + 1][c] = Math.max(w1, w2);
        }
    }
}

import java.util.*;
public class Main {
	int [][][] dp=new int [101][202][51];
    public int max(int x,int y) {
    	if(abs(x)>abs(y)) {
    		return abs(x);
    	}
    	return abs(y);
    }
    public int abs(int x) {
    	if(x<0) {
    		return x*-1;
    	}
    	return x;
    }
	public int val(char[] s) {
		int v=0,p=1;
		for(char c:s) {
			if(c=='T') {
				p*=-1;
				continue;
			}
		v+=p;}
	return v;}
	public int solve(int v,int index,char[] s,int size,int n) {

		if(index==size&&n%2==0) {
			return v;
		}
		if(n<0||(index==size&&n%2==1)) {
			return Integer.MIN_VALUE;
		}
		if(dp[index][v+100][n]!=-1) {
			return dp[index][v+100][n];
		}
		int y=solve(v,index+1,s,size,n);
		if(n%2==0) {
			int x;
			if(s[index]=='T') {
				s[index]='F';
				x=solve(val(s),index+1,s,size,n-1);
				s[index]='T';
			}
			else {
				s[index]='T';
				x=solve(val(s),index+1,s,size,n-1);
				s[index]='F';
			}
			return dp[index][v+100][n]=max(max(x,v),y);

		}
		else {
			int x=0;
			if(s[index]=='T') {
				s[index]='F';
				x=solve(val(s),index+1,s,size,n-1);
				s[index]='T';
			}
			else {
				s[index]='T';
				x=solve(val(s),index+1,s,size,n-1);
				s[index]='F';
			}
			return dp[index][v+100][n]=max(y,x);
		}

	}

	public static void main(String[]agrs) {

		Scanner input=new Scanner(System.in);
		String arr=input.nextLine();
		int n=input.nextInt();
		char[] s=arr.toCharArray();
		Main obj=new Main();
		for(int i=0;i<=100;i++) {
			for(int j=0;j<=201;j++) {
				for(int t=0;t<=50;t++) {
					obj.dp[i][j][t]=-1;
				}
			}
		}
		System.out.print(obj.solve(obj.val(s),0, s,arr.length(),n));
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class C {
    static int[][][] DP;
    static String s;
    static int[] M = { 1, -1 };
    static int inf = 10000000;

    public static int get(int index, int com, int m) {
        if (com < 0)
            return -inf;
        if (index == s.length())
            if (com == 0)
                return 0;
            else
                return -inf;
        if (DP[index][com][m] != -1)
            return DP[index][com][m];
        if (s.charAt(index) == 'F') {
            int max = -inf;
            for (int i = 0; i <= com; i++) {
                if (i % 2 == 0)
                    max = Math.max(max, M[m] + get(index + 1, com - i, m));
                else
                    max = Math.max(max, get(index + 1, com - 1, 1 - m));
            }
            return DP[index][com][m] = max;
        } else {
            int max = -inf;
            for (int i = 0; i <= com; i++) {
                if (i % 2 == 0)
                    max = Math.max(max, get(index + 1, com, 1 - m));
                else
                    max = Math.max(max, M[m] + get(index + 1, com - 1, m));
            }
            return DP[index][com][m] = max;
        }

    }

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        s = in.readLine();
        int n = Integer.parseInt(in.readLine());
        DP = new int[s.length()][n + 1][2];
        for (int i = 0; i < DP.length; i++)
            for (int j = 0; j < DP[0].length; j++)
                DP[i][j][0] = DP[i][j][1] = -1;
        System.out.println(Math.max(get(0, n, 0), get(0, n, 1)));
    }
}

import java.io.*;
import java.util.Arrays;
import static java.lang.Integer.*;
public class E {
    static int [][][][] dp;
    static String info;
    final static int OFFSET = 200;
    //0 for forward, 1 for backward
    public static int runDP(int idx, int rem, int score, int dir){
        if(idx >= info.length() && rem == 0)
            return score < 0 ? score * -1 : score;
        if(rem < 0)
            return -(int)1e9;
        if(idx >= info.length())
            return -(int)1e9;
        int accessScore = score < 0 ? score + OFFSET : score;
        if(dp[idx][rem][accessScore][dir] != -1)
            return dp[idx][rem][accessScore][dir];
        int ans = 0;
        //try executing current instruction i times from 0 to rem
        for(int i = 0 ; i <= rem ; ++i){
            if(info.charAt(idx) == 'T'){
                if(i % 2 == 0)
                    ans = Math.max(ans, runDP(idx + 1, rem - i, score, 1 - dir));
                else{
                    int nscore = dir == 0 ? score + 1 : score - 1;
                    ans = Math.max(ans, runDP(idx + 1, rem - i, nscore, dir));
                }
            }else{
                if(i % 2 == 0){
                    int nscore = dir == 0 ? score + 1 : score - 1;
                    ans = Math.max(ans, runDP(idx + 1, rem - i, nscore, dir));
                }else{
                    ans = Math.max(ans, runDP(idx + 1, rem - i, score, 1 - dir));
                }
            }
        }
        return dp[idx][rem][accessScore][dir] = ans;
    }
    public static void main(String[] args)throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String in = br.readLine();
        info = in;
        int K =parseInt(br.readLine());
        dp = new int [in.length() + 1][K + 1][205][2];
        for(int i = 0 ; i < dp.length ; ++i)
            for(int j = 0 ; j < dp[i].length ; ++j)
                for(int k = 0 ; k < dp[i][j].length ; ++k)
                    Arrays.fill(dp[i][j][k], -1);
        int ans = runDP(0, K, 0, 0);
        System.out.println(ans);
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Egor Kulikov (egor@egork.net)
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskC solver = new TaskC();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskC {
	public void solve(int testNumber, InputReader in, OutputWriter out) {
		char[] commands = in.readString().toCharArray();
		int changes = in.readInt();
		boolean[][][] reachable = new boolean[commands.length + 1][2 * commands.length + 1][changes + 1];
		reachable[0][commands.length][changes] = true;
		for (int i = 0; i < commands.length; i++) {
			for (int j = commands.length - i; j <= commands.length + i; j++) {
				for (int k = 0; k <= changes; k++) {
					if (reachable[i][j][k]) {
						if (commands[i] == 'F') {
							reachable[i + 1][j + 1][k] = true;
							if (k != 0)
								reachable[i + 1][2 * commands.length - j][k - 1] = true;
						} else {
							reachable[i + 1][2 * commands.length - j][k] = true;
							if (k != 0)
								reachable[i + 1][j + 1][k - 1] = true;
						}
					}
				}
			}
		}
		int answer = 0;
		for (int i = 0; i <= 2 * commands.length; i++) {
			for (int j = 0; j <= changes; j += 2) {
				if (reachable[commands.length][i][j])
					answer = Math.max(answer, Math.abs(i - commands.length));
			}
		}
		out.printLine(answer);
	}
}

class InputReader {

	private InputStream stream;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int numChars;

	public InputReader(InputStream stream) {
		this.stream = stream;
	}

	public int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int readInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public String readString() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuffer res = new StringBuffer();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	public static boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	}

class OutputWriter {
	private final PrintWriter writer;

	public OutputWriter(OutputStream outputStream) {
		writer = new PrintWriter(outputStream);
	}

	public OutputWriter(Writer writer) {
		this.writer = new PrintWriter(writer);
	}

	public void print(Object...objects) {
		for (int i = 0; i < objects.length; i++) {
			if (i != 0)
				writer.print(' ');
			writer.print(objects[i]);
		}
	}

	public void printLine(Object...objects) {
		print(objects);
		writer.println();
	}

	public void close() {
		writer.close();
	}

	}

import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }
}

class TaskC {
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        char[] commands = in.next().toCharArray();
        int changes = in.nextInt();
        boolean[][][] reachable = new boolean[commands.length + 1][2 * commands.length + 1][changes + 1];

        reachable[0][commands.length][changes] = true;
        for (int i = 0; i < commands.length; i++) {
            for (int j = commands.length - i; j <= commands.length + i; j++) {
                for (int k = 0; k <= changes; k++) {
                    if (reachable[i][j][k]) {
                        if (commands[i] == 'F') {
                            reachable[i + 1][j + 1][k] = true;
                            if (k != 0)
                                reachable[i + 1][2 * commands.length - j][k - 1] = true;
                        } else {
                            reachable[i + 1][2 * commands.length - j][k] = true;
                            if (k != 0)
                                reachable[i + 1][j + 1][k - 1] = true;
                        }
                    }
                }
            }
        }
        int answer = 0;
        for (int i = 0; i <= 2 * commands.length; i++) {
            for (int j = 0; j <= changes; j += 2) {
                if (reachable[commands.length][i][j])
                    answer = Math.max(answer, Math.abs(i - commands.length));
            }
        }
        out.println(answer);
    }
}

class InputReader {
    public BufferedReader reader;
    public StringTokenizer tokenizer;
    public InputReader(InputStream stream){
        reader = new BufferedReader(new InputStreamReader(stream));
        tokenizer = null;
    }
    public String next(){
        while(tokenizer == null || !tokenizer.hasMoreTokens()){
            try{
                tokenizer = new StringTokenizer(reader.readLine());
            }catch (IOException e){
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken();
    }
    public int nextInt(){
        return Integer.parseInt((next()));
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Turtle
{
	static char []s;
	static boolean [][][][] visited;
	static int N;
	static boolean []reached;

	static int offset=100;
	public static void dp(int idx,int sum,int n,int sign)
	{

		//System.out.println(sum+" "+n);

		if(idx==s.length)
		{

			if(n%2==1)
				return;
			reached[sum+offset]=true;
			return;
		}
		if(visited[idx][sum+offset][n][sign+1])
			return;
		if(s[idx]=='T')
		{
			dp(idx+1,sum,n,-1*sign);
			if(n>0)
				dp(idx+1,sum+sign,n-1,sign);
		}
		else
		{
			dp(idx+1,sum+sign,n,sign);
			if(n>0)
				dp(idx+1,sum,n-1,-1*sign);
		}
		visited[idx][sum+offset][n][sign+1]=true;
	}
	public static void main(String[] args) throws IOException {
		Scanner sc=new Scanner(System.in);
		 s=sc.next().toCharArray();
		N=sc.nextInt();
		int T=0;
		for(char c:s)
			if(c=='T')
				T++;

		if(T<=N)
		{
			int x=N-T;
			System.out.println(x%2==0?s.length:s.length-1);
			return;
		}

		visited=new boolean[205][205][55][3];
		reached=new boolean[205];
		dp(0,0,N,1);
		int ans=0;

		for( int i=0;i<205;i++)
		{
			if(reached[i])
			{
				ans=Math.max(ans, Math.abs(i-offset));
			}
		}
		System.out.println(ans);
	}
	static class Scanner
	{
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream s){	br = new BufferedReader(new InputStreamReader(s));}

		public String next() throws IOException
		{
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public int nextInt() throws IOException {return Integer.parseInt(next());}

		public long nextLong() throws IOException {return Long.parseLong(next());}

		public String nextLine() throws IOException {return br.readLine();}

		public double nextDouble() throws IOException
		{
			String x = next();
			StringBuilder sb = new StringBuilder("0");
			double res = 0, f = 1;
			boolean dec = false, neg = false;
			int start = 0;
			if(x.charAt(0) == '-')
			{
				neg = true;
				start++;
			}
			for(int i = start; i < x.length(); i++)
				if(x.charAt(i) == '.')
				{
					res = Long.parseLong(sb.toString());
					sb = new StringBuilder("0");
					dec = true;
				}
				else
				{
					sb.append(x.charAt(i));
					if(dec)
						f *= 10;
				}
			res += Long.parseLong(sb.toString()) / f;
			return res * (neg?-1:1);
		}

		public boolean ready() throws IOException {return br.ready();}

}
}

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;

/**
 * @author Ivan Pryvalov (ivan.pryvalov@gmail.com)
 */
public class Codeforces_Round_96_Div1_C implements Runnable{

	private void solve() throws IOException {
		String commands = scanner.nextLine();
		char[] cmd = commands.toCharArray();
		int N = commands.length();
		int count = scanner.nextInt();
		//count = Math.min(count, N);

		int[][][] c = new int[N+1][2*N+3][2]; //steps,position,dir
		for (int steps = 0; steps <= N; steps++) {
			for (int pos = 0; pos < 2*N+3; pos++) {
				for (int dir = 0; dir < 2; dir++) {
					c[steps][pos][dir] = -1;
				}
			}
		}
		int posOffset = N+1;
		c[0][posOffset][0] = count;

		for (int steps = 1; steps <= N; steps++) {
			for (int pos = 0; pos < 2*N+3; pos++) {
				for (int dir = 0; dir < 2; dir++) {
					int movesLeft = c[steps-1][pos][dir];
					int step = cmd[steps-1]=='F' ? 1 : 0;
					for(int useNow = 0;
							useNow<=1 && movesLeft>=0;
							useNow++, step=1-step, movesLeft--){
						int pos1 = pos;
						int dir1 = dir;
						if (step==1){
							pos1 = dir==0? pos1+1 : pos1-1;
						}else{
							dir1 = 1-dir;
						}
						if (c[steps][pos1][dir1]<0){
							c[steps][pos1][dir1] = movesLeft;
						}else{
							c[steps][pos1][dir1] = Math.max(c[steps][pos1][dir1], movesLeft);
						}
					}
				}
			}
		}

		int answer = -2;
		for(int pos=0; pos< 2*N+3; pos++){
			for(int dir=0; dir<=1; dir++){
				int movesLeft = c[N][pos][dir];
				if (movesLeft>=0 && movesLeft%2==0){
					answer = Math.max(answer, Math.abs(pos-posOffset));
				}
			}
		}
		out.println(answer);
	}

	/////////////////////////////////////////////////
	final int BUF_SIZE = 1024 * 1024 * 8;//important to read long-string tokens properly
	final int INPUT_BUFFER_SIZE = 1024 * 1024 * 8 ;
	final int BUF_SIZE_INPUT = 1024;

	final int BUF_SIZE_OUT = 1024;

	boolean inputFromFile = false;
	String filenamePrefix = "A-small-attempt0";
	String inSuffix = ".in";
	String outSuffix = ".out";

	//InputStream bis;
	//OutputStream bos;
	PrintStream out;
	ByteScanner scanner;
	ByteWriter writer;

	@Override
	public void run() {
		try{
			InputStream bis = null;
			OutputStream bos = null;
			//PrintStream out = null;
			if (inputFromFile){
				File baseFile = new File(getClass().getResource("/").getFile());
				bis = new BufferedInputStream(
						new FileInputStream(new File(
								baseFile, filenamePrefix+inSuffix)),
								INPUT_BUFFER_SIZE);
				bos = new BufferedOutputStream(
						new FileOutputStream(
								new File(baseFile, filenamePrefix+outSuffix)));
				out = new PrintStream(bos);
			}else{
				bis = new BufferedInputStream(System.in, INPUT_BUFFER_SIZE);
				bos = new BufferedOutputStream(System.out);
				out = new PrintStream(bos);
			}
			scanner = new ByteScanner(bis, BUF_SIZE_INPUT, BUF_SIZE);
			writer = new ByteWriter(bos, BUF_SIZE_OUT);

			solve();
			out.flush();
		}catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	public interface Constants{
		final static byte ZERO = '0';//48 or 0x30
		final static byte NINE = '9';
		final static byte SPACEBAR = ' '; //32 or 0x20
		final static byte MINUS = '-'; //45 or 0x2d

		final static char FLOAT_POINT = '.';
	}

	public static class EofException extends IOException{
	}

	public static class ByteWriter implements Constants {

		int bufSize = 1024;
		byte[] byteBuf = new byte[bufSize];
		OutputStream os;

		public ByteWriter(OutputStream os, int bufSize){
			this.os = os;
			this.bufSize = bufSize;
		}

		public void writeInt(int num) throws IOException{
	         int byteWriteOffset = byteBuf.length;
	         if (num==0){
	        	 byteBuf[--byteWriteOffset] = ZERO;
	         }else{
	        	 int numAbs = Math.abs(num);
	        	 while (numAbs>0){
	        		 byteBuf[--byteWriteOffset] = (byte)((numAbs % 10) + ZERO);
	        		 numAbs /= 10;
	        	 }
	        	 if (num<0)
	        		 byteBuf[--byteWriteOffset] = MINUS;
	         }
	         os.write(byteBuf, byteWriteOffset, byteBuf.length - byteWriteOffset);
		}

		/**
		 * Please ensure ar.length <= byteBuf.length!
		 *
		 * @param ar
		 * @throws IOException
		 */
		public void writeByteAr(byte[] ar) throws IOException{
			for (int i = 0; i < ar.length; i++) {
				byteBuf[i] = ar[i];
			}
			os.write(byteBuf,0,ar.length);
		}

		public void writeSpaceBar() throws IOException{
			byteBuf[0] = SPACEBAR;
			os.write(byteBuf,0,1);
		}

	}

	public static class ByteScanner implements Constants{

		InputStream is;

		public ByteScanner(InputStream is, int bufSizeInput, int bufSize){
			this.is = is;
			this.bufSizeInput = bufSizeInput;
			this.bufSize = bufSize;

			byteBufInput = new byte[this.bufSizeInput];
			byteBuf = new byte[this.bufSize];
		}

		public ByteScanner(byte[] data){
			byteBufInput = data;
			bufSizeInput = data.length;
			bufSize = data.length;
			byteBuf = new byte[bufSize];
			byteRead = data.length;
			bytePos = 0;
		}

		private int bufSizeInput;
		private int bufSize;

		byte[] byteBufInput;
		byte by=-1;
		int byteRead=-1;
		int bytePos=-1;

		byte[] byteBuf;
		int totalBytes;

		boolean eofMet = false;

		private byte nextByte() throws IOException{

			if (bytePos<0 || bytePos>=byteRead){
				byteRead = is==null? -1: is.read(byteBufInput);
				bytePos=0;
				if (byteRead<0){
					byteBufInput[bytePos]=-1;//!!!
					if (eofMet)
						throw new EofException();
					eofMet = true;
				}
			}
			return byteBufInput[bytePos++];
		}

		/**
		 * Returns next meaningful character as a byte.

		 *
		 * @return
		 * @throws IOException
		 */
		public byte nextChar() throws IOException{
			while ((by=nextByte())<=0x20);
			return by;
		}

		/**
		 * Returns next meaningful character OR space as a byte.

		 *
		 * @return
		 * @throws IOException
		 */
		public byte nextCharOrSpacebar() throws IOException{
			while ((by=nextByte())<0x20);
			return by;
		}

	    /**
	     * Reads line.
	     *
	     * @return
	     * @throws IOException
	     */
	    public String nextLine() throws IOException {
            readToken((byte)0x20);
            return new String(byteBuf,0,totalBytes);
	    }

	    public byte[] nextLineAsArray() throws IOException {
            readToken((byte)0x20);
            byte[] out = new byte[totalBytes];
            System.arraycopy(byteBuf, 0, out, 0, totalBytes);
            return out;
	    }

	    /**
	     * Reads token. Spacebar is separator char.
	     *
	     * @return
	     * @throws IOException
	     */
	    public String nextToken() throws IOException {
            readToken((byte)0x21);
            return new String(byteBuf,0,totalBytes);
	    }

	    /**
	     * Spacebar is included as separator char
	     *
	     * @throws IOException
	     */
	    private void readToken() throws IOException {
            readToken((byte)0x21);
	    }

	    private void readToken(byte acceptFrom) throws IOException {
            totalBytes = 0;
            while ((by=nextByte())<acceptFrom);
            byteBuf[totalBytes++] = by;
            while ((by=nextByte())>=acceptFrom){
                byteBuf[totalBytes++] = by;
            }
	    }

	    public int nextInt() throws IOException{
			readToken();
			int num=0, i=0;
			boolean sign=false;
			if (byteBuf[i]==MINUS){
				sign = true;
				i++;
			}
			for (; i<totalBytes; i++){
				num*=10;
				num+=byteBuf[i]-ZERO;
			}
			return sign?-num:num;
		}

		public long nextLong() throws IOException{
			readToken();
			long num=0;
			int i=0;
			boolean sign=false;
			if (byteBuf[i]==MINUS){
				sign = true;
				i++;
			}
			for (; i<totalBytes; i++){
				num*=10;
				num+=byteBuf[i]-ZERO;
			}
			return sign?-num:num;
		}

		/*
		//TODO test Unix/Windows formats
		public void toNextLine() throws IOException{
			while ((ch=nextChar())!='\n');
		}
		*/

		public double nextDouble() throws IOException{
			readToken();
			char[] token = new char[totalBytes];
			for (int i = 0; i < totalBytes; i++) {
				token[i] = (char)byteBuf[i];
			}
			return Double.parseDouble(new String(token));
		}

	}

	public static void main(String[] args) {
		new Codeforces_Round_96_Div1_C().run();
	}

}

/**
 * Created by ckboss on 14-9-3.
 */

import java.util.*;

public class O {

    static int len, n;
    static int[][][][] dp = new int[2][200][500][100]; ///base is 200;
    static boolean[][][][] vis = new boolean[2][200][500][100];
    static String cmd;

    static int dfs(int dir, int cd, int pos, int cur) {

        if (cur < 0) return 0;
        if (cd == len) {
            if (cur > 0) return 0;
            else return Math.abs(pos - 200);
        }

        if (vis[dir][cd][pos][cur] == true)
            return dp[dir][cd][pos][cur];
        int ret = 0;

        int mv = (dir == 1) ? -1 : 1;

        if (cmd.charAt(cd) == 'T')
            ret = Math.max(ret, Math.max(dfs(1 ^ dir, cd + 1, pos, cur), dfs(dir, cd + 1, pos + mv, cur - 1)));
        else if (cmd.charAt(cd) == 'F')
            ret = Math.max(ret, Math.max(dfs(dir, cd + 1, pos + mv, cur), dfs(1 ^ dir, cd + 1, pos, cur - 1)));

        vis[dir][cd][pos][cur] = true;
        dp[dir][cd][pos][cur] = ret;

        return ret;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        cmd = in.nextLine();
        len = cmd.length();

        n = in.nextInt();

        int ans = -999999;
        for (int i = n; i >= 0; i -= 2) {
            ans = Math.max(ans, dfs(0, 0, 200, i));
        }

        System.out.println(ans);
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;

public class E133 {
	BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
	StringTokenizer st = null;

	private void solution() throws IOException {
		String s = nextToken();
		int n = nextInt();
		int nap[] = new int[2];
		nap[0] = -1;
		nap[1] = 1;
		int dp[][][] = new int[s.length() + 1][n + 1][2];
		for (int i = 0; i <= s.length(); i++) {
			for (int j = 0; j <= n; j++) {
				for (int k = 0; k < 2; k++) {
					dp[i][j][k] = -100;
				}
			}
		}
		dp[0][0][0] = dp[0][0][1] = 0;
		for (int i = 1; i <= s.length(); i++) {
			for (int j = 0; j <= n; j++) {
				for (int k = 0; k < 2; k++) {
					if (s.charAt(i - 1) == 'F') {
						dp[i][j][k] = Math.max(dp[i][j][k], dp[i - 1][j][k]
								+ nap[k]);
						if (j > 0) {
							dp[i][j][k] = Math.max(dp[i][j][k],
									dp[i - 1][j - 1][1 - k]);
						}
					} else {
						if (j > 0) {
							dp[i][j][k] = Math.max(dp[i][j][k],
									dp[i - 1][j - 1][k] + nap[k]);
						}
						dp[i][j][k] = Math
								.max(dp[i][j][k], dp[i - 1][j][1 - k]);
					}
				}
			}
		}
		int ans = 0;
		for (int j = 0; j <= n; j++) {
			if (j % 2 != n % 2)
				continue;
			for (int k = 0; k < 2; k++) {
				ans = Math.max(ans, dp[s.length()][j][k]);
			}
		}
		System.out.println(ans);
	}

	String nextToken() throws IOException {
		if (st == null || !st.hasMoreTokens()) {
			st = new StringTokenizer(bf.readLine());
		}
		return st.nextToken();
	}

	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}

	public void print(int a[]) {
		for (int i = 0; i < a.length; i++) {
			System.out.print(a[i] + " ");
		}
	}

	public static void main(String args[]) throws IOException {
		new E133().solution();
	}
}

import java.lang.*;
import java.math.BigInteger;
import java.io.*;
import java.util.*;

public class Solution implements Runnable{
    public static BufferedReader br;
    public static PrintWriter out;
    public static StringTokenizer stk;
    public static boolean isStream = true;

    public static void main(String[] args) throws IOException {
    	if (isStream) {
            br = new BufferedReader(new InputStreamReader(System.in));
        } else {
            br = new BufferedReader(new FileReader("in.txt"));
        }
        out = new PrintWriter(System.out);
        new Thread(new Solution()).start();
    }

    public void loadLine() {
        try {
            stk = new StringTokenizer(br.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String nextLine() {
        try {
            return br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    public String nextWord() {
        while (stk==null||!stk.hasMoreTokens()) loadLine();
        return stk.nextToken();
    }

    public Integer nextInt() {
        while (stk==null||!stk.hasMoreTokens()) loadLine();
        return Integer.valueOf(stk.nextToken());
    }

    public Long nextLong() {
        while (stk==null||!stk.hasMoreTokens()) loadLine();
        return Long.valueOf(stk.nextToken());
    }

    public Double nextDouble() {
        while (stk==null||!stk.hasMoreTokens()) loadLine();
        return Double.valueOf(stk.nextToken());
    }

    public Float nextFloat() {
        while (stk==null||!stk.hasMoreTokens()) loadLine();
        return Float.valueOf(stk.nextToken());
    }

    int f(int d) {
    	return d==0 ? 1 : -1;
    }

    public void run() {
    	char[] com = nextWord().toCharArray();
    	int k = nextInt();
    	int n = com.length;
    	boolean[][][][] dp = new boolean[n+1][k+1][2][310]; // Comm pos, changed, turt dir, turt pos
    	dp[0][0][0][150] = true;
    	for (int i = 0; i < n; ++i) {
    		for (int j = 0; j <= k; ++j) {
    			for (int d = 0; d <= 1; ++d) {
    				for (int p = 0; p <= 300; ++p) {
            			if (dp[i][j][d][p]) {
            				if (com[i] == 'T') {
            					dp[i+1][j][1-d][p] = true;
            					if ((k-j) > 0) dp[i+1][j+1][d][p+f(d)] = true;
            					if ((k-j) > 1) dp[i][j+2][d][p] = true;
            				} else {
            					dp[i+1][j][d][p+f(d)] = true;
            					if ((k-j) > 0) dp[i+1][j+1][1-d][p] = true;
            					if ((k-j) > 1) dp[i][j+2][d][p] = true;
            				}
            			}
            		}
        		}
    		}
    	}
    	int ans = 0;
		for (int d = 0; d <= 1; ++d) {
			for (int p = 0; p <= 300; ++p) {
    			if (dp[n][k][d][p]) {
    				ans = Math.max(ans, Math.abs(150-p));
    			}
    		}
		}
		out.println(ans);
    	out.flush();
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.StringTokenizer;

public class magic2 {
	static char[] input;
	static int[][][] memo;
	public static void main(String[] args) throws Exception {
		FasterScanner sc = new FasterScanner();
		PrintWriter out = new PrintWriter(System.out);
		input = sc.next().toCharArray();
		int N = sc.nextInt();
		memo = new int[input.length][2][N+1];
		for(int[][] x : memo)
			for(int[] y : x)
				Arrays.fill(y,987654321);
		int ans = 0;
		for(int a=N;a>=0;a-=2){
			ans = Math.max(ans,DP(0,0,a));
			ans = Math.max(ans,DP(0,1,a));
		}
		out.println(ans);
		out.close();
	}

	private static int DP(int pos, int dir, int changes) {
		if(changes<0)return -987654;
		if(pos==input.length){
			if(changes==0)return 0;
			return -987654;
		}
		if(memo[pos][dir][changes]!=987654321)return memo[pos][dir][changes];
		int change = 1;
		if(dir==0)change = -1;
		int ans = -987654321;
		if(input[pos]=='F'){
			//forward
			ans=Math.max(ans,change+DP(pos+1,dir,changes));
			ans=Math.max(ans,DP(pos+1,1-dir,changes-1));
		}
		else{
			//turn
			ans=Math.max(ans,DP(pos+1,1-dir,changes));
			ans=Math.max(ans,change+DP(pos+1,dir,changes-1));
		}
		return memo[pos][dir][changes]=ans;
	}

	private static int fix(char c) {
		if(c=='S')return 0;
		return c-'a'+1;
	}

	static class FasterScanner{
		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;

		public FasterScanner(){
			stream = System.in;
		}
		int read(){
			if(numChars==-1)
				throw new InputMismatchException();
			if(curChar>=numChars){
				curChar = 0;
				try{
					numChars = stream.read(buf);
				} catch (IOException e){
					throw new InputMismatchException();
				}
				if(numChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		boolean isSpaceChar(int c){
			return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;
		}
		boolean isEndline(int c){
			return c=='\n'||c=='\r'||c==-1;
		}
		int nextInt(){
			return Integer.parseInt(next());
		}
		long nextLong(){
			return Long.parseLong(next());
		}
		double nextDouble(){
			return Double.parseDouble(next());
		}
		String next(){
			int c = read();
			while(isSpaceChar(c))
				c=read();
			StringBuilder res = new StringBuilder();
			do{
				res.appendCodePoint(c);
				c=read();
			} while(!isSpaceChar(c));
			return res.toString();
		}
		String nextLine(){
			int c = read();
			while(isEndline(c))
				c=read();
			StringBuilder res = new StringBuilder();
			do{
				res.appendCodePoint(c);
				c = read();
			}while(!isEndline(c));
			return res.toString();
		}

	}
	static class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		public FastScanner(InputStream in) throws Exception {
			br = new BufferedReader(new InputStreamReader(in));
			st = new StringTokenizer(br.readLine().trim());
		}

		public int numTokens() throws Exception {
			if (!st.hasMoreTokens()) {
				st = new StringTokenizer(br.readLine().trim());
				return numTokens();
			}
			return st.countTokens();
		}

		public boolean hasNext() throws Exception {
			if (!st.hasMoreTokens()) {
				st = new StringTokenizer(br.readLine().trim());
				return hasNext();
			}
			return true;
		}

		public String next() throws Exception {
			if (!st.hasMoreTokens()) {
				st = new StringTokenizer(br.readLine().trim());
				return next();
			}
			return st.nextToken();
		}

		public double nextDouble() throws Exception {
			return Double.parseDouble(next());
		}

		public float nextFloat() throws Exception {
			return Float.parseFloat(next());
		}

		public long nextLong() throws Exception {
			return Long.parseLong(next());
		}

		public int nextInt() throws Exception {
			return Integer.parseInt(next());
		}

		public String nextLine() throws Exception {
			return br.readLine();
		}
	}

}

import java.util.Scanner;

public class E {

    static int L;
    static String s;
    static boolean[][][][]calculated;
    static int ans = 0;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        s = sc.next();
        L = s.length();
        int n = sc.nextInt();
        calculated = new boolean[205][L+1][n+1][2];
        calc(100, 0, n, 1);
        System.out.println(ans);
    }

    private static void calc(int pos, int ind, int change, int orient) {
        if (L==ind) {
            if (change%2==0)
                ans = Math.max(ans, Math.abs(pos-100));
            return;
        }
        if (change < 0)
            return;
        if (calculated[pos][ind][change][orient])
            return;
        calculated[pos][ind][change][orient] = true;
        int dx = -1;
        if (orient==1)
            dx = 1;
        if (s.charAt(ind)=='F') {
            calc(pos+dx, ind+1, change, orient);
            calc(pos, ind+1, change-1, 1-orient);
        }
        else {
            calc(pos, ind+1, change, 1-orient);
            calc(pos+dx, ind+1, change-1, orient);
        }
    }
}

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
 public class realfast implements Runnable {
    private static final int INF = (int) 1e9;

    public  void solve() throws IOException
    {
      String s= readString();

      int n = readInt();

      int dp[][][][]= new int [s.length()+1][n+1][211][2];

      for(int i=0;i<s.length();i++)
        for(int j=0;j<=n;j++)
            for(int k=0;k<=210;k++)
                for(int l=0;l<=1;l++)
                    dp[i][j][k][l]=-1;

      int val = dp(dp,0,0,n,s,0);

      out.println(val);

    }
    public  int dp(int dp[][][][], int i, int dist, int n,String s, int check)
    {
        if(i==s.length())
        {
           if(n==0)
           {
             return Math.abs(dist);
           }
           else
            return 0;
        }

        if(dp[i][n][100+dist][check]!=-1){

            return dp[i][n][100+dist][check];
        }

        if(s.charAt(i)=='T')
        {
            if(check==0)
            {
                for(int k=n;k>=0;k=k-2)
             dp[i][n][dist+100][check]=Math.max(dp[i][n][dist+100][check],dp(dp,i+1,dist,k,s,(check+1)%2));
             if(n>0)
             {
              for(int k=n;k>=1;k=k-2)
             dp[i][n][dist+100][check] =Math.max( dp(dp,i+1,dist+1,k-1,s,check),dp[i][n][100+dist][check]);
             }
            }
            else
            {
              for(int k=n;k>=0;k=k-2)
             dp[i][n][dist+100][check]=Math.max(dp[i][n][dist+100][check],dp(dp,i+1,dist,k,s,(check+1)%2));
             if(n>0)
             {
               for(int k=n;k>=1;k=k-2)
              dp[i][n][dist+100][check]= Math.max(dp(dp,i+1,dist-1,k-1,s,check),dp[i][n][dist+100][check]);
             }
            }
        }
        else
        {
            if(check==0){
                for(int k=n;k>=0;k=k-2)
                dp[i][n][dist+100][check]=Math.max(dp[i][n][dist+100][check],dp(dp,i+1,dist+1,k,s,0));
                if(n>0){
                for(int k=n;k>=1;k=k-2)
                dp[i][n][dist+100][check]=Math.max(dp[i][n][dist+100][check],dp(dp,i+1,dist,k-1,s,1));
                }
            }
            else
            {
                for(int k=n;k>=0;k=k-2)
                dp[i][n][dist+100][check]=Math.max(dp[i][n][dist+100][check],dp(dp,i+1,dist-1,k,s,1));
                if(n>0){
                    for(int k=n;k>=1;k=k-2)
                    dp[i][n][dist+100][check]=Math.max(dp[i][n][dist+100][check],dp(dp,i+1,dist,k-1,s,0));
                }
            }
        }
        return dp[i][n][dist+100][check];
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static void main(String[] args) {
        new Thread(null, new realfast(), "", 128 * (1L << 20)).start();
    }

    private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
    private BufferedReader reader;
    private StringTokenizer tokenizer;
    private PrintWriter out;

    @Override
    public void run() {
        try {
            if (ONLINE_JUDGE || !new File("input.txt").exists()) {
                reader = new BufferedReader(new InputStreamReader(System.in));
                out = new PrintWriter(System.out);
            } else {
                reader = new BufferedReader(new FileReader("input.txt"));
                out = new PrintWriter("output.txt");
            }
            solve();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                // nothing
            }
            out.close();
        }
    }

    private String readString() throws IOException {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            tokenizer = new StringTokenizer(reader.readLine());
        }
        return tokenizer.nextToken();
    }

    @SuppressWarnings("unused")
    private int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    @SuppressWarnings("unused")
    private long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    @SuppressWarnings("unused")
    private double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }
}
class edge implements Comparable<edge>{
    int u ;
    int v ;
    int val;
    edge(int u1, int v1 , int val1)
    {
       this.u=u1;
       this.v=v1;
       this.val=val1;
    }
    public int compareTo(edge e)
    {
        return this.val-e.val;
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class LogoTurtle {

	static class Scanner{
		BufferedReader br=null;
		StringTokenizer tk=null;
		public Scanner(){
			br=new BufferedReader(new InputStreamReader(System.in));
		}
		public String next() throws IOException{
			while(tk==null || !tk.hasMoreTokens())
				tk=new StringTokenizer(br.readLine());
			return tk.nextToken();
		}
		public int nextInt() throws NumberFormatException, IOException{
			return Integer.valueOf(next());
		}
		public double nextDouble() throws NumberFormatException, IOException{
			return Double.valueOf(next());
		}
	}

	static Integer[][][][] dp;

	static int dp(int pos, int quedan, int dir, int idx){
		int npos = pos + 100;
		if (dp[npos][quedan][dir][idx] != null)
			return dp[npos][quedan][dir][idx];
		if (idx == commands.length){
			dp[npos][quedan][dir][idx] = (quedan % 2 == 0)? Math.abs(pos) : 0;
			return dp[npos][quedan][dir][idx];
		}
		int ret = 0;
		// no change
		if (commands[idx] == 'T')
			ret = dp(pos, quedan, (dir + 1) % 2, idx + 1);
		else{
			int np = ((dir == 0)? pos + 1: pos - 1);
			ret = dp(np, quedan, dir, idx + 1);
		}
		if (quedan == 0){
			dp[npos][quedan][dir][idx] = ret;
			return ret;
		}
		// change
		if (commands[idx] == 'F')
			ret = Math.max(ret, dp(pos, quedan - 1, (dir + 1) % 2, idx + 1));
		else{
			int np = ((dir == 0)? pos + 1: pos - 1);
			ret = Math.max(ret, dp(np, quedan - 1, dir, idx + 1));
		}
		dp[npos][quedan][dir][idx] = ret;
		return ret;
	}

	static char[] commands;
	static int N;

	public static void main(String args[]) throws IOException{
		Scanner sc = new Scanner();
		commands = sc.next().toCharArray();
		N = sc.nextInt();
		dp = new Integer[205][N + 1][2][commands.length + 1];
		System.out.println(dp(0, N, 0, 0));
	}

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class LogoTurtle {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		char[] c = br.readLine().toCharArray();
		int n = Integer.parseInt(br.readLine());

		int[][][] dist = new int[c.length][n+1][2];

		for (int j = 0; j < n+1; j++) {
			if ((c[0] == 'T' && j%2 == 1) || (c[0] == 'F' && j%2 == 0)) {
				dist[0][j][0] = 1;
				dist[0][j][1] = -1;
			}
		}

		for (int i = 1; i < c.length; i++) {
			if (c[i] == 'T') {
				dist[i][0][0] = dist[i-1][0][1];
				dist[i][0][1] = dist[i-1][0][0];
			} else {
				dist[i][0][0] = dist[i-1][0][0]+1;
				dist[i][0][1] = dist[i-1][0][1]-1;
			}
		}

		for (int i = 1; i < c.length; i++) {
			for (int j = 1; j < n+1; j++) {
				for (int k = 0; k < 2; k++) {
					if (c[i] == 'T') {
						dist[i][j][k] = Math.max(dist[i-1][j][k^1], dist[i-1][j-1][k]+(k==0?1:-1));
					} else {
						dist[i][j][k] = Math.max(dist[i-1][j][k]+(k==0?1:-1), dist[i-1][j-1][k^1]);
					}
				}
			}
		}

		int maxDist = 0;
		for (int j = n, maxn; j >= 0; j-=2) {
			maxn = Math.max(dist[c.length-1][j][0], dist[c.length-1][j][1]);
			maxDist = Math.max(maxDist, maxn);
		}

		System.out.println(maxDist);
	}

}

import java.util.Arrays;
import java.util.Scanner;
import static java.lang.Math.*;

public class turtle {
    public static void debug(Object... obs) {
        System.out.println(Arrays.deepToString(obs));
    }

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);

        String s = sc.next();
        int k = sc.nextInt();
        int n = s.length();

        int[][][] dp = new int[n + 1][k + 1][2];
        int[]signum=new int[n];
        int si=1;
        for(int i=0;i<s.length();i++)
        {
            if(s.charAt(i)=='T') si*=-1;
            signum[i]=si;
        }

        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= k; j++) {
                dp[i][j][0] = Integer.MIN_VALUE;
                dp[i][j][1] = Integer.MAX_VALUE;
            }
        }

        dp[0][0][0] = 0;
        dp[0][0][1] = 0;

        for (int i = 1; i <= n; i++) {
            int trn = 0;
            int inc = 1;
            if (s.charAt(i - 1) == 'T') {
                trn = 1;
            }
            for (int j = 0; j <= k; j++) {
                for (int f = 0; f <= j; f++) {
                    int d = (j - f + trn) % 2;
                    int sgn = 1;
                    if (i > 1) {
                        sgn = (signum[i-2]==-1) ? ((f % 2 == 0) ? -1 : 1)
                                : ((f % 2 == 0) ? 1 : -1);
                    }

                    //debug(i, j, f, d, sgn);

                    if(dp[i - 1][f][1] == Integer.MAX_VALUE || dp[i - 1][f][0] == Integer.MIN_VALUE) continue;

                    dp[i][j][0] = Math.max(dp[i][j][0], dp[i - 1][f][0] + sgn
                            * (1 - d) * inc);
                    dp[i][j][0] = Math.max(dp[i][j][0], dp[i - 1][f][1] + sgn
                            * (1 - d) * inc);
                    dp[i][j][1] = Math.min(dp[i][j][1], dp[i - 1][f][0] + sgn
                            * (1 - d) * inc);
                    dp[i][j][1] = Math.min(dp[i][j][1], dp[i - 1][f][1] + sgn
                            * (1 - d) * inc);
                }
            }
        }

        int ma = Integer.MIN_VALUE;
        for (int j = 0; j < 2; j++)
            if (dp[n][k][j] != Integer.MAX_VALUE
                    && dp[n][k][j] != Integer.MIN_VALUE)
                ma = Math.max(ma, Math.abs(dp[n][k][j]));
        System.out.println(ma);
    }
}

import java.io.*;
import java.util.Locale;
import java.util.StringTokenizer;

public class A implements Runnable {

    private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

    private BufferedReader in;
    private PrintWriter out;
    private StringTokenizer tok = new StringTokenizer("");

    private void init() throws FileNotFoundException {
        Locale.setDefault(Locale.US);
        String fileName = "";
        if (ONLINE_JUDGE && fileName.isEmpty()) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        } else {
            if (fileName.isEmpty()) {
                in = new BufferedReader(new FileReader("input.txt"));
                out = new PrintWriter("output.txt");
            } else {
                in = new BufferedReader(new FileReader(fileName + ".in"));
                out = new PrintWriter(fileName + ".out");
            }
        }
    }

    String readString() {
        while (!tok.hasMoreTokens()) {
            try {
                tok = new StringTokenizer(in.readLine());
            } catch (Exception e) {
                return null;
            }
        }
        return tok.nextToken();
    }

    int readInt() {
        return Integer.parseInt(readString());
    }

    long readLong() {
        return Long.parseLong(readString());
    }

    double readDouble() {
        return Double.parseDouble(readString());
    }

    int[] readIntArray(int size) {
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = readInt();
        }
        return a;
    }

    public static void main(String[] args) {
        //new Thread(null, new A(), "", 128 * (1L << 20)).start();
        new A().run();
    }

    long timeBegin, timeEnd;

    void time() {
        timeEnd = System.currentTimeMillis();
        System.err.println("Time = " + (timeEnd - timeBegin));
    }

    @Override
    public void run() {
        try {
            timeBegin = System.currentTimeMillis();
            init();
            solve();
            out.close();
            time();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    final int OFFSET = 100;
    final int MAX_ANSWER = 200;

    void solve() throws IOException {
        char[] s = readString().toCharArray();
        int n = readInt();
        boolean[][][][] dp = new boolean[s.length + 1][n + 1][2][MAX_ANSWER + 1];
        dp[0][0][0][OFFSET] = true;
        for (int i = 1; i <= s.length; i++) {
            for (int j = 0; j <= n; j++) {
                for (int d = 0; d < MAX_ANSWER; d++) {
                    if (dp[i - 1][j][0][d]) {
                        if (s[i - 1] == 'T') {
                            for (int changes = j; changes <= n; changes++) {
                                if (j % 2 == changes % 2) {
                                    dp[i][changes][1][d] = true;
                                } else {
                                    dp[i][changes][0][d + 1] = true;
                                }
                            }
                        } else {
                            for (int changes = j; changes <= n; changes++) {
                                if (j % 2 == changes % 2) {
                                    dp[i][changes][0][d + 1] = true;
                                } else {
                                    dp[i][changes][1][d] = true;
                                }
                            }
                        }
                    }

                    if (dp[i - 1][j][1][d]) {
                        if (s[i - 1] == 'T') {
                            for (int changes = j; changes <= n; changes++) {
                                if (j % 2 == changes % 2) {
                                    dp[i][changes][0][d] = true;
                                } else {
                                    dp[i][changes][1][d - 1] = true;
                                }
                            }
                        } else {
                            for (int changes = j; changes <= n; changes++) {
                                if (j % 2 == changes % 2) {
                                    dp[i][changes][1][d - 1] = true;
                                } else {
                                    dp[i][changes][0][d] = true;
                                }
                            }
                        }
                    }
                }
            }
        }
        int answer = 0;
        for (int d = 0; d <= MAX_ANSWER; d++) {
            if (dp[s.length][n][0][d] || dp[s.length][n][1][d]) {
                answer = Math.max(answer, Math.abs(OFFSET - d));
            }
        }
        out.println(answer);
    }
}

import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigDecimal;
import java.math.BigInteger;

import static java.lang.Math.*;

// Solution is at the bottom of code

public class C implements Runnable{

	final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

	BufferedReader in;
	OutputWriter out;
	StringTokenizer tok = new StringTokenizer("");

	public static void main(String[] args){
		new Thread(null, new C(), "", 128 * (1L << 20)).start();
	}

	/////////////////////////////////////////////////////////////////////

	void init() throws FileNotFoundException{
		Locale.setDefault(Locale.US);

		if (ONLINE_JUDGE){
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new OutputWriter(System.out);
		}else{
			in = new BufferedReader(new FileReader("input.txt"));
			out = new OutputWriter("output.txt");
		}
	}

	////////////////////////////////////////////////////////////////

	long timeBegin, timeEnd;

	void time(){
		timeEnd = System.currentTimeMillis();
		System.err.println("Time = " + (timeEnd - timeBegin));
	}

	void debug(Object... objects){
		if (ONLINE_JUDGE){
			for (Object o: objects){
				System.err.println(o.toString());
			}
		}
	}

	/////////////////////////////////////////////////////////////////////

	public void run(){
		try{
			timeBegin = System.currentTimeMillis();
			Locale.setDefault(Locale.US);

			init();
			solve();

			out.close();
			time();
		}catch (Exception e){
			e.printStackTrace(System.err);
			System.exit(-1);
		}
	}

	/////////////////////////////////////////////////////////////////////

	String delim = " ";

	String readString() throws IOException{
		while(!tok.hasMoreTokens()){
			try{
				tok = new StringTokenizer(in.readLine());
			}catch (Exception e){
				return null;
			}
		}

		return tok.nextToken(delim);
	}

	String readLine() throws IOException{
		return in.readLine();
	}

	/////////////////////////////////////////////////////////////////

	final char NOT_A_SYMBOL = '\0';

	char readChar() throws IOException{
		int intValue = in.read();

		if (intValue == -1){
			return NOT_A_SYMBOL;
		}

		return (char) intValue;
	}

	char[] readCharArray() throws IOException{
		return readLine().toCharArray();
	}

	/////////////////////////////////////////////////////////////////

	int readInt() throws IOException {
		return Integer.parseInt(readString());
	}

	int[] readIntArray(int size) throws IOException {
		int[] array = new int[size];

		for (int index = 0; index < size; ++index){
			array[index] = readInt();
		}

		return array;
	}

	int[] readSortedIntArray(int size) throws IOException {
		Integer[] array = new Integer[size];

		for (int index = 0; index < size; ++index) {
			array[index] = readInt();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}

	int[] readIntArrayWithDecrease(int size) throws IOException {
		int[] array = readIntArray(size);

		for (int i = 0; i < size; ++i) {
			array[i]--;
		}

		return array;
	}

	///////////////////////////////////////////////////////////////////

	int[][] readIntMatrix(int rowsCount, int columnsCount) throws IOException {
		int[][] matrix = new int[rowsCount][];

		for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
			matrix[rowIndex] = readIntArray(columnsCount);
		}

		return matrix;
	}

	int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) throws IOException {
		int[][] matrix = new int[rowsCount][];

		for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
			matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
		}

		return matrix;
	}

	///////////////////////////////////////////////////////////////////

	long readLong() throws IOException{
		return Long.parseLong(readString());
	}

	long[] readLongArray(int size) throws IOException{
		long[] array = new long[size];

		for (int index = 0; index < size; ++index){
			array[index] = readLong();
		}

		return array;
	}

	////////////////////////////////////////////////////////////////////

	double readDouble() throws IOException{
		return Double.parseDouble(readString());
	}

	double[] readDoubleArray(int size) throws IOException{
		double[] array = new double[size];

		for (int index = 0; index < size; ++index){
			array[index] = readDouble();
		}

		return array;
	}

	////////////////////////////////////////////////////////////////////

	BigInteger readBigInteger() throws IOException {
		return new BigInteger(readString());
	}

	BigDecimal readBigDecimal() throws IOException {
		return new BigDecimal(readString());
	}

	/////////////////////////////////////////////////////////////////////

	Point readPoint() throws IOException{
		int x = readInt();
		int y = readInt();
		return new Point(x, y);
	}

	Point[] readPointArray(int size) throws IOException{
		Point[] array = new Point[size];

		for (int index = 0; index < size; ++index){
			array[index] = readPoint();
		}

		return array;
	}

	/////////////////////////////////////////////////////////////////////

	List<Integer>[] readGraph(int vertexNumber, int edgeNumber)
	throws IOException{
		@SuppressWarnings("unchecked")
		List<Integer>[] graph = new List[vertexNumber];

		for (int index = 0; index < vertexNumber; ++index){
			graph[index] = new ArrayList<Integer>();
		}

		while (edgeNumber-- > 0){
			int from = readInt() - 1;
			int to = readInt() - 1;

			graph[from].add(to);
			graph[to].add(from);
		}

		return graph;
	}

	/////////////////////////////////////////////////////////////////////

	static class IntIndexPair {

		static Comparator<IntIndexPair> increaseComparator = new Comparator<C.IntIndexPair>() {

			@Override
			public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
				int value1 = indexPair1.value;
				int value2 = indexPair2.value;

				if (value1 != value2) return value1 - value2;

				int index1 = indexPair1.index;
				int index2 = indexPair2.index;

				return index1 - index2;
			}
		};

		static Comparator<IntIndexPair> decreaseComparator = new Comparator<C.IntIndexPair>() {

			@Override
			public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
				int value1 = indexPair1.value;
				int value2 = indexPair2.value;

				if (value1 != value2) return -(value1 - value2);

				int index1 = indexPair1.index;
				int index2 = indexPair2.index;

				return index1 - index2;
			}
		};

		int value, index;

		public IntIndexPair(int value, int index) {
			super();
			this.value = value;
			this.index = index;
		}

		public int getRealIndex() {
			return index + 1;
		}
	}

	IntIndexPair[] readIntIndexArray(int size) throws IOException {
		IntIndexPair[] array = new IntIndexPair[size];

		for (int index = 0; index < size; ++index) {
			array[index] = new IntIndexPair(readInt(), index);
		}

		return array;
	}

	/////////////////////////////////////////////////////////////////////

	static class OutputWriter extends PrintWriter {

		final int DEFAULT_PRECISION = 12;

		protected int precision;
		protected String format, formatWithSpace;

		{
			precision = DEFAULT_PRECISION;

			format = createFormat(precision);
			formatWithSpace = format + " ";
		}

		public OutputWriter(OutputStream out) {
			super(out);
		}

		public OutputWriter(String fileName) throws FileNotFoundException {
			super(fileName);
		}

		public int getPrecision() {
			return precision;
		}

		public void setPrecision(int precision) {
			precision = max(0, precision);
			this.precision = precision;

			format = createFormat(precision);
			formatWithSpace = format + " ";
		}

		private String createFormat(int precision){
			return "%." + precision + "f";
		}

		@Override
		public void print(double d){
			printf(format, d);
		}

		public void printWithSpace(double d){
			printf(formatWithSpace, d);
		}

		public void printAll(double...d){
			for (int i = 0; i < d.length - 1; ++i){
				printWithSpace(d[i]);
			}

			print(d[d.length - 1]);
		}

		@Override
		public void println(double d){
			printlnAll(d);
		}

		public void printlnAll(double... d){
			printAll(d);
			println();
		}
	}

	/////////////////////////////////////////////////////////////////////

	static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
	static final int[][] steps8 = {
			{-1, 0}, {1, 0}, {0, -1}, {0, 1},
			{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
	};

	static final boolean check(int index, int lim){
		return (0 <= index && index < lim);
	}

	/////////////////////////////////////////////////////////////////////

	static final boolean checkBit(int mask, int bit){
		return (mask & (1 << bit)) != 0;
	}

	/////////////////////////////////////////////////////////////////////

	static final long getSum(int[] array) {
		long sum = 0;
		for (int value: array) {
			sum += value;
		}

		return sum;
	}

	static final Point getMinMax(int[] array) {
		int min = array[0];
		int max = array[0];

		for (int index = 0, size = array.length; index < size; ++index, ++index) {
			int value = array[index];

			if (index == size - 1) {
				min = min(min, value);
				max = max(max, value);
			} else {
				int otherValue = array[index + 1];

				if (value <= otherValue) {
					min = min(min, value);
					max = max(max, otherValue);
				} else {
					min = min(min, otherValue);
					max = max(max, value);
				}
			}
		}

		return new Point(min, max);
	}

	/////////////////////////////////////////////////////////////////////

	final char REVERSE = 'T';

	void solve() throws IOException {
		char[] commands = readCharArray();
		int commandsCount = commands.length;

		int n = readInt();

		int ZERO = commandsCount + 1;
		int MAX_X = ZERO * 2;

		int[][][][] dp = new int[2][2][2][n + 1];

		int[][] minCurDp = dp[0][0];
		int[][] minNextDp = dp[0][1];

		int[][] maxCurDp = dp[1][0];
		int[][] maxNextDp = dp[1][1];

		int POSITIVE_INF = MAX_X + 1;
		int NEGATIVE_INF = -POSITIVE_INF;

		for (int direction = 0; direction < 2; ++direction) {
			Arrays.fill(minCurDp[direction], POSITIVE_INF);
			Arrays.fill(maxCurDp[direction], NEGATIVE_INF);

			Arrays.fill(minNextDp[direction], POSITIVE_INF);
			Arrays.fill(maxNextDp[direction], NEGATIVE_INF);
		}

		minCurDp[0][n] = ZERO;
		maxCurDp[0][n] = ZERO;

		for (int command = 0; command < commandsCount; ++command) {
			boolean isReverse = (commands[command] == REVERSE);

			if (isReverse) {
				for (int direction = 0; direction < 2; ++direction) {
					int delta = (direction == 0 ? 1 : -1);

					for (int changes = n; changes > 0; --changes) {
						if (minCurDp[direction][changes] != POSITIVE_INF) {
							minNextDp[1 - direction][changes] = min(minNextDp[1 - direction][changes], minCurDp[direction][changes]);
							minNextDp[direction][changes - 1] = min(minNextDp[direction][changes - 1], minCurDp[direction][changes] + delta);

							maxNextDp[1 - direction][changes] = max(maxNextDp[1 - direction][changes], maxCurDp[direction][changes]);
							maxNextDp[direction][changes - 1] = max(maxNextDp[direction][changes - 1], maxCurDp[direction][changes] + delta);
						}
					}

					if (minCurDp[direction][0] != POSITIVE_INF) {
						minNextDp[1 - direction][0] = min(minNextDp[1 - direction][0], minCurDp[direction][0]);
						maxNextDp[1 - direction][0] = max(maxNextDp[1 - direction][0], maxCurDp[direction][0]);
					}
				}
			} else {
				for (int direction = 0; direction < 2; ++direction) {
					int delta = (direction == 0 ? 1 : -1);

					for (int changes = n; changes > 0; --changes) {
						if (minCurDp[direction][changes] != POSITIVE_INF) {
							minNextDp[1 - direction][changes - 1] = min(minNextDp[1 - direction][changes - 1], minCurDp[direction][changes]);
							minNextDp[direction][changes] = min(minNextDp[direction][changes], minCurDp[direction][changes] + delta);

							maxNextDp[1 - direction][changes - 1] = max(maxNextDp[1 - direction][changes - 1], maxCurDp[direction][changes]);
							maxNextDp[direction][changes] = max(maxNextDp[direction][changes], maxCurDp[direction][changes] + delta);
						}
					}

					if (minCurDp[direction][0] != POSITIVE_INF) {
						minNextDp[direction][0] = min(minNextDp[direction][0], minCurDp[direction][0] + delta);
						maxNextDp[direction][0] = max(maxNextDp[direction][0], maxCurDp[direction][0] + delta);
					}
				}
			}

			for (int direction = 0; direction < 2; ++direction) {
				for (int changes = 0; changes <= n; ++changes) {
					minCurDp[direction][changes] = minNextDp[direction][changes];
					maxCurDp[direction][changes] = maxNextDp[direction][changes];

					minNextDp[direction][changes] = POSITIVE_INF;
					maxNextDp[direction][changes] = NEGATIVE_INF;
				}
			}
		}

		int maxDelta = 0;
		for (int coord = 0; coord <= MAX_X; ++coord) {
			for (int changes = 0; changes <= n; changes += 2) {
				for (int direction = 0; direction < 2; ++direction) {
					if (minCurDp[direction][changes] != POSITIVE_INF) {
						maxDelta = max(maxDelta, abs(maxCurDp[direction][changes] - ZERO));
						maxDelta = max(maxDelta, abs(minCurDp[direction][changes] - ZERO));
					}
				}
			}
		}

		out.println(maxDelta);
	}
}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class cf132c {
  static int n,m,oo=987654321;;
  static String v;
  static Integer[][][] memo;
  public static void main(String[] args) {
    FastIO in = new FastIO(), out = in;
    v = in.next().trim();
    n = in.nextInt();
    m = v.length();
    memo = new Integer[2][m][n+1];
    out.println(Math.max(go(0,n,0),go(0,n,1)));
    out.close();
  }
  static int go(int pos, int left, int dir) {
    if(left < 0) return -oo;
    if(pos == m) {
      return left%2==0?0:-oo;
    }
    if(memo[dir][pos][left] != null)
      return memo[dir][pos][left];
    int ans = -oo;
    char comm = v.charAt(pos);
    ans = Math.max(ans, go(pos+1,left-(comm=='T'?0:1),1-dir));
    ans = Math.max(ans, 2*dir-1 + go(pos+1,left-(comm=='F'?0:1),dir));
    return memo[dir][pos][left] = ans;
  }
  static class FastIO extends PrintWriter {
    BufferedReader br;
    StringTokenizer st;

    public FastIO() {
      this(System.in,System.out);
    }
    public FastIO(InputStream in, OutputStream out) {
      super(new BufferedWriter(new OutputStreamWriter(out)));
      br = new BufferedReader(new InputStreamReader(in));
      scanLine();
    }
    public void scanLine() {
      try {
        st = new StringTokenizer(br.readLine().trim());
      } catch(Exception e) {
        throw new RuntimeException(e.getMessage());
      }
    }
    public int numTokens() {
      if(!st.hasMoreTokens()) {
        scanLine();
        return numTokens();
      }
      return st.countTokens();
    }
    public String next() {
      if(!st.hasMoreTokens()) {
        scanLine();
        return next();
      }
      return st.nextToken();
    }
    public double nextDouble() {
      return Double.parseDouble(next());
    }
    public long nextLong() {
      return Long.parseLong(next());
    }
    public int nextInt() {
      return Integer.parseInt(next());
    }
  }
}

import java.io.*;
import java.util.*;

public class Template implements Runnable {

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

    void init() throws FileNotFoundException {
        try {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        } catch (Exception e) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        }
    }

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            try {
                tok = new StringTokenizer(in.readLine(), " :");
            } catch (Exception e) {
                return null;
            }
        }
        return tok.nextToken();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    int[] readIntArray(int size) throws IOException {
        int[] res = new int[size];
        for (int i = 0; i < size; i++) {
            res[i] = readInt();
        }
        return res;
    }

    long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }

    <T> List<T>[] createGraphList(int size) {
        List<T>[] list = new List[size];
        for (int i = 0; i < size; i++) {
            list[i] = new ArrayList<>();
        }
        return list;
    }

    public static void main(String[] args) {
        new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start();
    }

    long timeBegin, timeEnd;

    void time() {
        timeEnd = System.currentTimeMillis();
        System.err.println("Time = " + (timeEnd - timeBegin));
    }

    long memoryTotal, memoryFree;

    void memory() {
        memoryFree = Runtime.getRuntime().freeMemory();
        System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10)
                + " KB");
    }

    public void run() {
        try {
            timeBegin = System.currentTimeMillis();
            memoryTotal = Runtime.getRuntime().freeMemory();
            init();
            solve();
            out.close();
            if (System.getProperty("ONLINE_JUDGE") == null) {
                time();
                memory();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    void solve() throws IOException {
        char[] a = readString().toCharArray();
        int n = readInt();

        int AXIS = 2 * a.length + 5;

        boolean[][][][] dp = new boolean[a.length + 1][AXIS][n + 1][2];
        int ZERO_OFFSET = a.length + 2;
        dp[0][ZERO_OFFSET][0][0] = true;
        for (int step = 0; step < a.length; step++) {
            for (int nowPos = 0; nowPos < AXIS; nowPos++) {
                for (int oldCount = 0; oldCount <= n; oldCount++) {
                    for (int dir = 0; dir < 2; dir++) {
                        if (!dp[step][nowPos][oldCount][dir]) continue;
                        for (int turnCount = 0; turnCount <= n - oldCount; turnCount++) {
                            char res;
                            if (turnCount % 2 == 0) {
                                res = a[step];
                            } else {
                                res = a[step] == 'F' ? 'T' : 'F';
                            }
                            if (res == 'T') {
                                dp[step + 1][nowPos][oldCount + turnCount][1 - dir] = true;
                            } else {
                                dp[step + 1][nowPos + (dir == 0 ? +1 : -1)][oldCount + turnCount][dir] = true;
                            }
                        }
                    }
                }
            }
        }

        int max = 0;
        for (int pos = 0; pos < AXIS; pos++) {
            for (int dir = 0; dir < 2; dir++) {
                if (dp[a.length][pos][n][dir]) {
                    max = Math.max(max, Math.abs(ZERO_OFFSET - pos));
                }
            }
        }
        out.println(max);
    }

}

import java.util.*;
public class C132 {
    static int INF = 10000;
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        char[] commands = s.next().toCharArray();
        int m = commands.length;
        int n = s.nextInt();
        int[][][][] best = new int[m+1][2][n+1][2];
        // best[up to command k][using c changes]
        for (int d = 0; d < 2; d++) {
            best[0][d][0][0] = 0;
            best[0][d][0][1] = 0;
            for (int c = 1; c <= n; c++) {
                best[0][d][c][0] = INF;
                best[0][d][c][1] = -INF;
            }
        }
        for (int k = 1; k <= m; k++) {
            for (int c = 0; c <= n; c++) {
                for (int d = 0; d < 2; d++) {
                    int favLeft = INF;
                    int favRight = -INF;
                    for (int q = 0; q < 2; q++) {
                        for (int C = c-1; C >= 0; C-=2) {
                            int b;
                            if (commands[k-1]=='F') b = best[k-1][1-d][C][q];
                            else b = best[k-1][d][C][q]+((d==0)?1:-1);
                            if (Math.abs(b) < INF/2) {
                                favLeft = Math.min(favLeft, b);
                                favRight = Math.min(favRight, b);
                            }
                        }
                        for (int C = c; C >= 0; C-=2) {
                            int b;
                            if (commands[k-1]=='T') b = best[k-1][1-d][C][q];
                            else b = best[k-1][d][C][q]+((d==0)?1:-1);
                            if (Math.abs(b) < INF/2) {
                                favLeft = Math.min(favLeft, b);
                                favRight = Math.min(favRight, b);
                            }
                        }
                        //System.out.printf("%d,%d,%d: %d%n", k, d, c, best[k][d][c]);
                    }
                    best[k][d][c][0] = favLeft;
                    best[k][d][c][1] = favRight;
                }
            }
        }
        int besty = 0;
        for (int d = 0; d < 2; d++) {
            for (int q = 0; q < 2; q++) {
                if (Math.abs(best[m][d][n][q]) < INF/2)
                    besty = Math.max(besty, Math.abs(best[m][d][n][q]));
            }
        }
        System.out.println(besty);

    }
}

import javax.sound.sampled.Line;
import java.awt.Point;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.math.BigInteger.*;

import java.math.MathContext;
import java.util.*;
public class C{

    void solve()throws Exception
    {
       char[]s=nextString().toCharArray();
       int changes=nextInt();
        int add=s.length;
       boolean[][][][]dp=new boolean[2][s.length+1][2*s.length+1][changes+1];//dir,atCommand,at,changes
        dp[0][0][0+add][0]=true;
        dp[1][0][0+add][0]=true;

        for(int ch=0;ch<=changes;ch++)
            for(int at=0;at<s.length;at++)
                for(int atPoint=-add;atPoint<=add;atPoint++)
                    for(int dir=0;dir<=1;dir++)
                        if(dp[dir][at][atPoint+add][ch])
                        {
                            char c=s[at];
                            /*
                            if(ch==1 && at==3 && dir==0 && atPoint==3)
                                System.out.println(dp[dir][at][atPoint+add][ch]);
                                */
                            for(int curChange=0;curChange+ch<=changes;curChange++)
                            {
                                int x=curChange%2;
                                int nch=ch+curChange;
                                int ndir=dir;
                                char curCommand;
                                if(x==0)
                                    curCommand=c;
                                else
                                    curCommand=(char)('F'+'T'-c);
                                if(curCommand=='T')
                                    ndir=1-dir;
                                int nPoint=atPoint;
                                if(curCommand=='F')
                                {
                                    if(ndir==0)
                                        nPoint++;
                                    else
                                        nPoint--;
                                }
                                dp[ndir][at+1][nPoint+add][nch]=true;
                            }
                        }
      int res=0;
      for(int atPoint=0;atPoint<=s.length;atPoint++)
          if(dp[0][s.length][atPoint+add][changes] || dp[1][s.length][atPoint+add][changes])
              res=atPoint;
        System.out.println(res);
    }

    ////////////
    BufferedReader reader;
    PrintWriter writer;
    StringTokenizer stk;
    void run()throws Exception
    {
        reader=new BufferedReader(new InputStreamReader(System.in));
        stk=null;
        writer=new PrintWriter(new PrintWriter(System.out));
        solve();
        reader.close();
        writer.close();
    }
    int nextInt()throws Exception
    {
        return Integer.parseInt(nextToken());
    }

    long nextLong()throws Exception
    {
        return Long.parseLong(nextToken());

    }
    double nextDouble()throws Exception
    {
        return Double.parseDouble(nextToken());

    }

    String nextString()throws Exception
    {
        return nextToken();
    }
    String nextLine()throws Exception
    {
        return reader.readLine();
    }
    String nextToken()throws Exception
    {
        if(stk==null || !stk.hasMoreTokens())
        {
            stk=new StringTokenizer(nextLine());
            return nextToken();

        }
        return stk.nextToken();
    }

    public static void main(String[]args) throws Exception
    {
        new C().run();
    }

}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class R96qCLogoTurtle {

	static char a[];
	static int n;
	static int dp[][][][];
	static int oo = 1000;
	static int L = oo - 100,R = oo + 100;

	public static void main(String args[] ) throws Exception {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	    PrintWriter w = new PrintWriter(System.out);

	    String in = br.readLine();
	    a = new char[in.length() + 1];
	    for(int i=0;i<a.length-1;i++)
	    	a[i] = in.charAt(i);

	    n = ip(br.readLine());

	    dp = new int[a.length][n+1][2][2];
	    for(int i=0;i<a.length;i++)
	    	for(int j=0;j<=n;j++)
	    		for(int k=0;k<2;k++)
	    		dp[i][j][k][0] = dp[i][j][k][1] = 10*oo;

	    int ans1 = solveMax(0,n,m(a[0]),0);
	    //System.out.println(ans1);

	    for(int i=0;i<a.length;i++)
	    	for(int j=0;j<=n;j++)
	    		for(int k=0;k<2;k++)
	    		dp[i][j][k][0] = dp[i][j][k][1] = 10*oo;

	    int ans2 = -1*solveMin(0,n,m(a[0]),0);
	    //System.out.println(ans2);

	    if(ans1 > 100)	ans1 = 0;
	    if(ans2 > 100)	ans2 = 0;

	    w.println(Math.max(ans1, ans2));
	    w.close();
	}

	public static int solveMax(int curr,int movesLeft,int currState,int direction){
		if(curr == a.length-1)
			return movesLeft == 0 ? 0 : -oo;
		if(dp[curr][movesLeft][currState][direction] == 10*oo){
			int ans = -oo;
			if(currState == 0)
				ans = Math.max(ans, solveMax(curr+1,movesLeft,m(a[curr+1]),direction) + ((direction == 0) ? 1 : -1) );
			else
				ans = Math.max(ans, solveMax(curr+1,movesLeft,m(a[curr+1]),1 - direction) );
			if(movesLeft > 0)
				ans = Math.max(ans, solveMax(curr,movesLeft-1,1-currState,direction));
			dp[curr][movesLeft][currState][direction] = ans;
		}
		//System.out.println(curr +  " " + movesLeft + " " + currState + " " + direction + " : " + dp[curr][movesLeft][currState][direction] );
		return dp[curr][movesLeft][currState][direction];
	}

	public static int solveMin(int curr,int movesLeft,int currState,int direction){
		if(curr == a.length-1)
			return movesLeft == 0 ? 0 : oo;
		if(dp[curr][movesLeft][currState][direction] == 10*oo){
			int ans = oo;
			if(currState == 0)
				ans = Math.min(ans, solveMin(curr+1,movesLeft,m(a[curr+1]),direction) + ((direction == 0) ? 1 : -1) );
			else
				ans = Math.min(ans, solveMin(curr+1,movesLeft,m(a[curr+1]),1 - direction) );
			if(movesLeft > 0)
				ans = Math.min(ans, solveMin(curr,movesLeft-1,1-currState,direction));
			dp[curr][movesLeft][currState][direction] = ans;
		}
		return dp[curr][movesLeft][currState][direction];
	}

	public static int m(char x){	return (x == 'F') ? 0 : 1;	}

	public static int ip(String s){		return Integer.parseInt(s);	}
}

import java.util.Arrays;
import java.util.Scanner;

public class LogoTurtle {
    private static String input;
    private static int[][][][] dp;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        input = sc.nextLine();
        int changes = sc.nextInt();

        dp = new int[2*(input.length()+1)][changes+1][2][input.length()+1];
        for (int i = 0; i < dp.length; i++) {
            for (int j = 0; j < dp[0].length; j++) {
                Arrays.fill(dp[i][j][0], -1);
                Arrays.fill(dp[i][j][1], -1);
            }
        }

        int res = f(0, 0, true, changes);
        System.out.println(res);
    }
    private static int f(int cmdIndex, int pos, boolean direction, int changes) {
        int cached = dp[pos+input.length()][changes][direction?0:1][cmdIndex];
        if(cached != -1) {
            return cached;
        }

        int res;

        // reached the end of the input
        if(cmdIndex == input.length()) {
            if(changes == 0) {
                res = Math.abs(pos);
            } else {
                res = -1;
            }
        } else {
            boolean isForward = input.charAt(cmdIndex)=='F';
            int delta = (direction?1:-1)*(isForward?1:0);

            // keeping the command
            int keepingNewPos = pos+delta;
            boolean keepingNewDirection = isForward?direction:!direction;
            int keeping = -1;

            int tmpChanges = changes;
            while(tmpChanges >= 0) {
                keeping = Math.max(keeping, f(cmdIndex+1, keepingNewPos, keepingNewDirection, tmpChanges));
                tmpChanges -= 2;
            }

            // inverting the command
            int nonKeeping = -1;
            int nonKeepingNewPos = pos+(direction?1:-1)*(!isForward?1:0);
            boolean nonKeepingNewDirection = (!isForward)?direction:!direction;
            tmpChanges = changes;
            while(tmpChanges-1 >= 0) {
                nonKeeping = Math.max(nonKeeping, f(cmdIndex+1, nonKeepingNewPos, nonKeepingNewDirection, tmpChanges-1));
                tmpChanges -= 2;
            }

            res = Math.max(keeping, nonKeeping);
        }

        dp[pos+input.length()][changes][direction?0:1][cmdIndex] = res;
        return res;
    }
}

import java.util.Scanner;

public class CF133E {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String commands = sc.next();
        int n = sc.nextInt();

        State[][][][] dp = new State[commands.length()+1][n+1][201][2];
        State init = State.valueOf(0);
        dp[0][0][100][0] = init;
        for (int i = 1; i < dp.length; i++) {
            boolean commandIsT = commands.charAt(i-1) == 'T';
            for (int j = 0; j < n+1; j++) {
                for (int k = 0; k <= 200; k++) {
                    for (int l = 0; l < 2; l++) {
                        State temp;
                        int dx = l == 0 ? -1 : 1;
                        if (commandIsT) {
                            if(dp[i-1][j][k][l] != null) {
                                temp = State.getBigger(dp[i-1][j][k][l], dp[i][j][k][(l+1)%2]);
                                dp[i][j][k][(l+1)%2] = temp;
                            }
                            if(j > 0 && dp[i-1][j-1][k][l] != null) {
                                temp = State.getBigger(dp[i-1][j-1][k][l].forward(dx), dp[i][j][k+dx][l]);
                                dp[i][j][k+dx][l] = temp;
                            }
                        }
                        else {
                            if(dp[i-1][j][k][l] != null) {
                                temp = State.getBigger(dp[i-1][j][k][l].forward(dx), dp[i][j][k+dx][l]);
                                dp[i][j][k+dx][l] = temp;
                            }
                            if(j > 0 && dp[i-1][j-1][k][l] != null) {
                                temp = State.getBigger(dp[i-1][j-1][k][l], dp[i][j][k][(l+1)%2]);
                                dp[i][j][k][(l+1)%2] = temp;
                            }
                        }
                        if(j > 1) dp[i][j][k][l] = State.getBigger(dp[i][j-2][k][l], dp[i][j][k][l]);
                    }
                }
            }
        }
        int max = 0;
        for (int i = 0; i <= 200; i++) {
            for (int j = 0; j < 2; j++) {
                if(dp[commands.length()][n][i][j] != null)
                    max = Math.max(max, dp[commands.length()][n][i][j].dist());
            }
        }
        System.out.println(max);
    }

    static class State {
        final int x;
        public State(int x) {
            this.x = x;
        }
        static State valueOf(int x) {
            return new State(x);
        }
        State forward(int dx) {
            return valueOf(x + dx);
        }
        int dist() {
            return Math.abs(x);
        }

        static State getBigger(State a, State b) {
            if (a == null) return b;
            if (b == null) return a;
            return a.dist() > b.dist() ? a : b;
        }

    }

}

import java.util.Arrays;
import java.util.Scanner;

public class F {
    static int[][][][] dp = new int[110][230][110][3];
    static String inp;

    public static int min(int index, int pos, int n, int direction) {
        if (index == inp.length() && n == 0)
            return Math.abs(pos);
        else if (index == inp.length())
            return Integer.MIN_VALUE;
        else if (dp[index][pos + 100][n][direction + 1] != -1)
            return dp[index][pos + 100][n][direction + 1];
        else {
            if (n == 0) {
                if (inp.charAt(index) == 'T') {
                    return dp[index][pos + 100][n][direction + 1] = min(
                            index + 1, pos, n, -direction);
                } else
                    return dp[index][pos + 100][n][direction + 1] = min(
                            index + 1, pos + direction, n, direction);
            }

            else {
                if (inp.charAt(index) == 'T') {
                    int max = min(index + 1, pos, n, -direction);
                    for (int i = 1; i <= n; i++) {
                        if (i % 2 == 0) {
                            max = Math.max(max,
                                    min(index + 1, pos, n - i, -direction));
                        } else {
                            max = Math.max(
                                    min(index + 1, pos + direction, n - i,
                                            direction), max);
                        }
                    }
                    return dp[index][pos + 100][n][direction + 1] = max;

                } else {
                    int max = min(index + 1, pos + direction, n, direction);
                    for (int i = 1; i <= n; i++) {
                        if (i % 2 == 0) {
                            max = Math.max(
                                    max,
                                    min(index + 1, pos + direction, n - i,
                                            direction));
                        } else {
                            max = Math.max(max,
                                    min(index + 1, pos, n - i, -direction));
                        }
                    }
                    return dp[index][pos + 100][n][direction + 1] = max;
                }
            }
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        inp = in.nextLine();

        int n = in.nextInt();
        for (int i = 0; i < dp.length; i++)
            for (int j = 0; j < dp[i].length; j++)
                for (int k = 0; k < dp[i][j].length; k++)
                    Arrays.fill(dp[i][j][k], -1);
        System.out.println(min(0, 0, n, 1));
    }
}

import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }
}

class TaskC {
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        char[] commands = in.next().toCharArray();
        int changes = in.nextInt();
        boolean[][][] reachable = new boolean[commands.length + 1][2 * commands.length + 1][changes + 1];

        reachable[0][commands.length][changes] = true;
        for (int i = 0; i < commands.length; i++) {
            for (int j = commands.length - i; j <= commands.length + i; j++) {
                for (int k = 0; k <= changes; k++) {
                    if (reachable[i][j][k]) {
                        if (commands[i] == 'F') {
                            reachable[i + 1][j + 1][k] = true;
                            if (k != 0)
                                reachable[i + 1][2 * commands.length - j][k - 1] = true;
                        } else {
                            reachable[i + 1][2 * commands.length - j][k] = true;
                            if (k != 0)
                                reachable[i + 1][j + 1][k - 1] = true;
                        }
                    }
                }
            }
        }
        int answer = 0;
        for (int i = 0; i <= 2 * commands.length; i++) {
            for (int j = 0; j <= changes; j += 2) {
                if (reachable[commands.length][i][j])
                    answer = Math.max(answer, Math.abs(i - commands.length));
            }
        }
        out.println(answer);
    }
}

class InputReader {
    public BufferedReader reader;
    public StringTokenizer tokenizer;
    public InputReader(InputStream stream){
        reader = new BufferedReader(new InputStreamReader(stream));
        tokenizer = null;
    }
    public String next(){
        while(tokenizer == null || !tokenizer.hasMoreTokens()){
            try{
                tokenizer = new StringTokenizer(reader.readLine());
            }catch (IOException e){
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken();
    }
    public int nextInt(){
        return Integer.parseInt((next()));
    }
}

import java.io.*;
import java.math.*;
import java.util.*;
import java.awt.geom.*;

import static java.lang.Math.*;

public class Solution implements Runnable {

	final int SHIFT = 200;

	boolean can [][][][];

	public void solve() throws Exception {
		String s = next();
		int m = s.length();
		int n = nextInt();
		can = new boolean [2][m+1][n+1][402];
		can[0][0][0][200] = true;
		int best = 0;
		for (int i = 0; i < s.length(); i++) {
			for (int pos = 0; pos <= 400; pos++)
				for (int use = 0; use <= n; use++)
					for (int dir = 0; dir < 2; dir++)
						if (can[dir][i][use][pos]) {
							// don't change
							if (s.charAt(i)=='F') {
								int nextpos = pos + (dir == 0 ? 1 : -1);
								int nextuse = use;
								int nextdir = dir;
								int nexti = i+1;
								can [nextdir][nexti][nextuse][nextpos] = true;
							}
							if (s.charAt(i)=='T') {
								int nextpos = pos;
								int nextuse = use;
								int nextdir = dir^1;
								int nexti = i+1;
								can [nextdir][nexti][nextuse][nextpos] = true;
							}
							// change
							if (use < n) {
								if (s.charAt(i)=='F') {
									int nextpos = pos;
									int nextuse = use + 1;
									int nextdir = dir ^ 1;
									int nexti = i+1;
									can [nextdir][nexti][nextuse][nextpos] = true;
								}
								if (s.charAt(i)=='T') {
									int nextpos = pos+ (dir == 0 ? 1 : -1);
									int nextuse = use + 1;
									int nextdir = dir;
									int nexti = i+1;
									can [nextdir][nexti][nextuse][nextpos] = true;
								}
							}
						}
		}
		for (int dir = 0; dir < 2; dir++)
			for (int pos = 0; pos <= 400; pos++)
				for (int use = 0; use <= n; use++)
					if (can[dir][m][use][pos] && (n-use)%2==0) {
						best = max (best, abs(pos - 200));
					}
		out.println(best);
	}

	/********************************************************************************************/
	/* THERE IS INPUT */

	BufferedReader in;
	PrintWriter out;
	StringTokenizer st;

	long stime=0;

	private String next() throws Exception {
		while (st == null || !st.hasMoreElements())
			st = new StringTokenizer(in.readLine());
		return st.nextToken();
	}

	private int nextInt() throws Exception {
		return Integer.parseInt(next());
	}

	private long nextLong() throws Exception {
		return Long.parseLong(next());
	}

	private double nextDouble() throws Exception {
		return Double.parseDouble(next());
	}

	public void run() {
		try {
			//Locale.setDefault(Locale.US);
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(new OutputStreamWriter(System.out));
			solve();
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			out.close();
		}
	}

	public static void main(String[] args) throws Exception {
		new Thread(null, new Solution(), "", 1 << 25).start();
	}

}

import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.util.*;
import java.util.regex.*;
import static java.lang.Math.*;
public class C {

    public C() throws Exception {
        String cmd = in.next();
        int m = cmd.length();
        int n = in.nextInt();
        boolean[][][] dp1 = new boolean[203][2][n+2];
        for (int i=1;i<=n+1;i+=2)
            dp1[101][0][i] = true;
        for (int i=1;i<=m;i++) {
            boolean[][][] dp2 = new boolean[203][2][n+2];
            for (int j=1;j<=201;j++) {
                for (int k=1;k<=n+1;k++) {
                    if (cmd.charAt(i-1)=='F') {
                        if (dp1[j-1][0][k])
                            dp2[j][0][k] = true;
                        if (dp1[j+1][1][k])
                            dp2[j][1][k] = true;

                        if (dp1[j][0][k-1])
                            dp2[j][1][k] = true;
                        if (dp1[j][1][k-1])
                            dp2[j][0][k] = true;
                    } else {
                        if (dp1[j][0][k])
                            dp2[j][1][k] = true;
                        if (dp1[j][1][k])
                            dp2[j][0][k] = true;

                        if (dp1[j-1][0][k-1])
                            dp2[j][0][k] = true;
                        if (dp1[j+1][1][k-1])
                            dp2[j][1][k] = true;
                    }
                }
            }
            dp1 = dp2;
        }

        int max = -1;
        for (int j=1;j<=201;j++) {
            if (dp1[j][0][n+1])
                max = max(max, abs(j-101));
            if (dp1[j][1][n+1])
                max = max(max, abs(j-101));
        }
        buf.append(max).append('\n');

        System.out.print(buf);
    }

    Scanner in = new Scanner(System.in);
    StringBuilder buf = new StringBuilder();
    public static void main(String[] args) throws Exception { // {{{
        new C();
    } // }}}
    public static void debug(Object... arr) { // {{{
        System.err.println(Arrays.deepToString(arr));
    } // }}}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class R96D2_E {
    static String inp;
    static int n;
    static int st;
    static int DP[][][][];

    public static int call(int i, int rem, int pos, int add) {
        if (i == n && (rem%2==0))
            return Math.abs(pos);
        if (i == n)
            return -1000000;
        if (pos == 0 && add == -1)
            add = 1;
        int d = add==-1?1:0;
        if(DP[i][rem][pos][d]!=-1)
            return DP[i][rem][pos][d];
        if (rem == 0) {
            if (inp.charAt(i) == 'F')
                return DP[i][rem][pos][d] = call(i + 1, rem, pos + add, add);
            else
                return DP[i][rem][pos][d] = call(i + 1, rem, pos, add * -1);
        } else {
            int res = 0;
            for (int j = 0; j <= rem; j++) {
                if ((inp.charAt(i) == 'F' && j % 2 == 0)
                        || (inp.charAt(i) == 'T' && j % 2 == 1))
                    res = Math.max(res, call(i + 1, rem - j, pos + add, add));
                else
                    res = Math.max(res, call(i + 1, rem - j, pos, -1 * add));
            }
            return DP[i][rem][pos][d] = res;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        // int n = Integer.parseInt(in.readLine());
        // String []s = in.readLine().split(" ");
        inp = in.readLine();
        n = inp.length();
        st = Integer.parseInt(in.readLine());
        DP = new int [n][st+1][n+2][2];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < st+1; j++) {
                for (int j2 = 0; j2 < n+2; j2++) {
                    for (int k = 0; k < 2; k++) {
                        DP[i][j][j2][k] = -1;
                    }
                }
            }
        }
        System.out.println(call(0, st, 0, 1));
    }
}

import static java.lang.Math.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.exit;
import static java.lang.System.arraycopy;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.fill;
import java.util.*;
import java.io.*;

public class Main {

	public static void main(String[] args) throws IOException {
		try {
			if (new File("input.txt").exists())
				System.setIn(new FileInputStream("input.txt"));
		} catch (SecurityException e) {
		}
		new Thread(null, new Runnable() {
			public void run() {
				try {
					new Main().run();
				} catch (Throwable e) {
					e.printStackTrace();
					exit(999);
				}
			}
		}, "1", 1 << 23).start();
	}

	BufferedReader in;
	PrintWriter out;
	StringTokenizer st = new StringTokenizer("");

	private void run() throws IOException {
		in = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);

		boolean dp[][][][] = new boolean[2][101][203][52]; // [inv][command][pos + 101][changed]
		dp[0][0][101][0] = true;
		String s = nextToken();
		int k = nextInt();

		for(int com = 0; com < s.length(); com++)
			for(int inv = 0; inv < 2; inv++)
			for(int pos = 0; pos < 203; pos ++)
				for(int ch = 0; ch <= k; ch++){
					if(!dp[inv][com][pos][ch]) continue;
					char c = s.charAt(com);
					int d = (inv == 0 ? 1 : (-1));
					if(c == 'F'){
						dp[inv][com + 1][pos + d][ch] = true;
						dp[1 - inv][com + 1][pos][ch + 1] = true;
					} else {
						dp[1 - inv][com + 1][pos][ch] = true;
						dp[inv][com + 1][pos + d][ch + 1] = true;
					}
				}
		int max = 0;
		for(int inv = 0; inv < 2; inv++)
			for(int pos = 0; pos < 203; pos++)
				for(int cha = k; cha >= 0; cha -= 2)
				if(dp[inv][s.length()][pos][cha])
					max = max(max, abs(pos - 101));
		out.println(max);
		in.close();
		out.close();
	}
	String nextToken() throws IOException {
		while (!st.hasMoreTokens())
			st = new StringTokenizer(in.readLine());
		return st.nextToken();
	}
	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}
	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}
	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}
	String nextLine() throws IOException {
		st = new StringTokenizer("");
		return in.readLine();
	}
	boolean EOF() throws IOException {
		while (!st.hasMoreTokens()) {
			String s = in.readLine();
			if (s == null)
				return true;
			st = new StringTokenizer(s);
		}
		return false;
	}
}

import java.util.*;

public class C {
    public static void main(String[] args) {
        new Solver().run();
    }

    static class Solver {
        static final Scanner sc = new Scanner(System.in);

        void run() {
            final char[] cs = sc.next().toCharArray();
            final int m = cs.length;
            final int n = sc.nextInt();

            boolean[][][][] dp = new boolean[m+1][n+2][201][2];
            int[] to = new int[]{1,-1};
            dp[0][0][100][0] = true;
            for(int i = 0; i < m; i++)
                for(int j = 0; j <= n; j++)
                    for(int k = 0; k < 201; k++)
                        for(int d = 0; d < 2; d++) {
                            if(dp[i][j][k][d]) {
                                if(cs[i] == 'T') {
                                    dp[i+1][j][k][d^1] = true;
                                    dp[i+1][j+1][k+to[d]][d] = true;
                                } else {
                                    dp[i+1][j+1][k][d^1] = true;
                                    dp[i+1][j][k+to[d]][d] = true;
                                }
                            }
                        }

            int res = 0;
            for(int i = n&1; i <= n; i+=2)
                for(int j = 0; j <= 200; j++)
                    for(int k = 0; k < 2; k++)
                        if(dp[m][i][j][k])
                            res = Math.max(res, Math.abs(j-100));

            System.out.println(res);
        }
    }
}

import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.util.logging.StreamHandler;

public class C {
	static Scanner in; static int next() throws Exception {return in.nextInt();};
//	static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;}
//	static BufferedReader in;
	static PrintWriter out;

	public static void main(String[] args) throws Exception {
		in = new Scanner(System.in);
//		in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
//		in = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);

        String s = new String(in.next());
        int n = s.length(), m = next();
        int x, max = 0, a, b, c, d, num = 0;
        TreeSet<Integer> set = new TreeSet<Integer>();
        set.add(1001);
        while (!set.isEmpty()) {
            x = set.first();
            set.remove(x);
     //       out.println(x);
            a = x/10000000; x %= 10000000;
            b = x/10000;    x %= 10000;
            c = x/10;       x %= 10;
            d = x;
            if (a == n) {
                if (max < Math.abs(c-100)){
                     max = Math.abs(c-100);
                    num = b;
                };
            }
            else if (a < n) {
                if (s.charAt(a) == 'F') set.add((a+1)*10000000 + b*10000 + (c+2*d-1)*10 + d);
                else set.add((a+1)*10000000 + b*10000 + c*10 + 1 - d);
                if (b < m) {
                    if (s.charAt(a) == 'F') set.add((a+1)*10000000 + (b+1)*10000 + c*10 + 1-d);
                    else set.add((a+1)*10000000 + (b+1)*10000 + (c+2*d-1)*10 + d);
                }
            }

        }
        out.println(max - (m-num)%2);
   //     out.println(num);

        out.println();
		out.close();
	}
}

import java.util.Arrays;
import java.util.Scanner;

public class LogoTurtle {
    private static String input;
    private static int[][][][] dp;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        input = sc.nextLine();
        int changes = sc.nextInt();

        dp = new int[2*(input.length()+1)][changes+1][2][input.length()+1];
        for (int i = 0; i < dp.length; i++) {
            for (int j = 0; j < dp[0].length; j++) {
                Arrays.fill(dp[i][j][0], -1);
                Arrays.fill(dp[i][j][1], -1);
            }
        }
        int res = f(0, 0, true, changes);
        System.out.println(res);
    }
    private static int f(int cmdIndex, int pos, boolean direction, int changes) {
        int cached = dp[pos+input.length()][changes][direction?0:1][cmdIndex];
        if(cached != -1) {
            return cached;
        }

        int res = 0;

        // reached the end of the input
        if(cmdIndex == input.length()) {
            if(changes == 0) {
                res = Math.abs(pos);
            } else {
                res = -1;
            }
        } else {
            boolean isForward = input.charAt(cmdIndex)=='F';
            int delta = (direction?1:-1)*(isForward?1:0);

            // keeping the command
            int keepingNewPos = pos+delta;
            boolean keepingNewDirection = isForward?direction:!direction;
            int keeping = -1;

            int tmpChanges = changes;
            while(tmpChanges >= 0) {
                keeping = Math.max(keeping, f(cmdIndex+1, keepingNewPos, keepingNewDirection, tmpChanges));
                tmpChanges -= 2;
            }

            // inverting the command
            int nonKeeping = -1;
            int nonKeepingNewPos = pos+(direction?1:-1)*(!isForward?1:0);
            boolean nonKeepingNewDirection = (!isForward)?direction:!direction;
            tmpChanges = changes;
            while(tmpChanges-1 >= 0) {
                nonKeeping = Math.max(nonKeeping, f(cmdIndex+1, nonKeepingNewPos, nonKeepingNewDirection, tmpChanges-1));
                tmpChanges -= 2;
            }

            res = Math.max(keeping, nonKeeping);
        }

        dp[pos+input.length()][changes][direction?0:1][cmdIndex] = res;
        return res;
    }
}

import java.io.*;
import java.util.*;

public class E {

    boolean DP[][][][];

    public boolean contains_printing_char(String s) {
	for (int i=0; i<s.length(); i++) {
	    if (s.charAt(i) == 'H' || s.charAt(i) =='Q' || s.charAt(i) =='9') return true;
	}
	return false;
    }

    public void read_input_and_solve() throws IOException {
	Scanner sc = new Scanner(System.in);
	String p = sc.nextLine();
	int changes = sc.nextInt();
	int n = p.length();
	DP = new boolean[n+1][2*n+1][changes+1][2];
	DP[0][n][0][0] = true;
	for (int t=1; t<=n; t++) {
	    char ch = p.charAt(t-1);
	    for (int h=0; h<=2*n; h++) {
		for (int c=0; c<=changes; c++) {
		    for (int dir=0; dir<2; dir++) {
			/* assign DP[t][h][c][dir] */
			boolean ans = false;
			int cc;
			if (ch=='T') cc=c; else cc=c-1;
			if (cc>=0) ans = ans || (DP[t-1][h][cc][1-dir]);

			if (ch=='F') cc=c; else cc=c-1;
			int ph = h + 1 - 2*dir;
			if (cc>=0 && ph>=0 && ph<=2*n) ans = ans || (DP[t-1][ph][cc][dir]);
			DP[t][h][c][dir] = ans;
			/*
			System.out.printf("DP[%d][%d][%d][%d] = %B\n", t, h, c, dir, ans);
			*/
		    }
		}
	    }
	}
	int maxd = 0;
	for (int h=0; h<=2*n; h++) {
	    for (int c=changes&1; c<=changes; c+=2) {
		for (int dir=0; dir<2; dir++) {
		    if (DP[n][h][c][dir]) maxd = Math.max(maxd, (Math.abs(h-n)));
		}
	    }
	}
	System.out.println(maxd);
    }

    public static void main(String[] args) throws IOException {
	(new E()).read_input_and_solve();
    }
}

import java.util.*;
public class C {
	static int [] reverse = new int [257];
	static int [][][] dp = new int [105][105][2];
	static char [] path;
	static int MIN_VAL = -(1<<20);
	public static void main (String [] arg) {
		Scanner sc = new Scanner(System.in);
		path = sc.next().toCharArray();
		int n = sc.nextInt();

		for (int i = 0; i<dp.length; ++i) for (int j = 0; j<dp[0].length; ++j) Arrays.fill(dp[i][j], MIN_VAL);
		int ans = recurse(n, 0, 1);
		for (int i = 0; i<dp.length; ++i) for (int j = 0; j<dp[0].length; ++j) Arrays.fill(dp[i][j], MIN_VAL);
		int ans2=recurse(n,0,0);
		System.out.println(Math.max(ans,ans2));
	}
	public static int recurse(int n, int pos, int orientation) {
		//System.err.println("@ " + n + " , " + pos + " , " + orientation);
		if (dp[n][pos][orientation] > MIN_VAL) return dp[n][pos][orientation];
		if (pos >= path.length) return ( n%2 == 0) ? 0 : MIN_VAL;
		int dir = (orientation == 0) ? -1 : 1;

		int best = MIN_VAL;
		if (n != 0) {
			if (path[pos] == 'F') best = Math.max(best, recurse(n-1, pos+1, 1-orientation));
			if (path[pos] == 'T') best = Math.max(best, dir + recurse(n-1, pos+1, orientation));
		}
		if (path[pos] == 'T') best = Math.max(best, recurse(n, pos+1, 1-orientation));
		if (path[pos] == 'F') best = Math.max(best, dir + recurse(n, pos+1, orientation));
		dp[n][pos][orientation] = best;
		return best;
	}

}

/**
 * Created by ckboss on 14-9-3.
 */

import java.util.*;

public class O {

    static int len, n;
    static int[][][][] dp = new int[2][200][500][100]; ///base is 200;
    static boolean[][][][] vis = new boolean[2][200][500][100];
    static String cmd;

    static int dfs(int dir, int cd, int pos, int cur) {

        if (cur < 0) return 0;
        if (cd == len) {
            if (cur > 0) return 0;
            else return Math.abs(pos - 200);
        }

        if (vis[dir][cd][pos][cur] == true)
            return dp[dir][cd][pos][cur];
        int ret = 0;

        int mv = (dir == 1) ? -1 : 1;

        if (cmd.charAt(cd) == 'T')
            ret = Math.max(ret, Math.max(dfs(1 ^ dir, cd + 1, pos, cur), dfs(dir, cd + 1, pos + mv, cur - 1)));
        else if (cmd.charAt(cd) == 'F')
            ret = Math.max(ret, Math.max(dfs(dir, cd + 1, pos + mv, cur), dfs(1 ^ dir, cd + 1, pos, cur - 1)));

        vis[dir][cd][pos][cur] = true;
        dp[dir][cd][pos][cur] = ret;

        return ret;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        cmd = in.nextLine();
        len = cmd.length();

        n = in.nextInt();

        int ans = -999999;
        for (int i = n; i >= 0; i -= 2) {
            ans = Math.max(ans, dfs(0, 0, 200, i));
        }

        System.out.println(ans);
    }
}

/**
 * Created by IntelliJ IDEA.
 * User: mac
 * Date: 11-12-3
 * Time: 下午9:56
 * To change this template use File | Settings | File Templates.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import java.util.StringTokenizer;

public class C {

    BufferedReader reader;
    StringTokenizer tokenizer;
    PrintWriter writer;

    void run() {
        try {
            reader = new BufferedReader(new InputStreamReader(System.in));
            tokenizer = null;
            writer = new PrintWriter(System.out);
            solve();
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    String nextToken() throws IOException {
        while (tokenizer == null || !tokenizer.hasMoreTokens())
            tokenizer = new StringTokenizer(reader.readLine());
        return tokenizer.nextToken();
    }

    int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }

    long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }

    double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }

    void solve() throws IOException {
        String com = nextToken();
        int nChange = nextInt();

        int maxDist = com.length() + 3;
        boolean[][][] am = new boolean[maxDist * 2][nChange + 1][2];
        am[maxDist][0][0] = true;

        for (int i = 0; i < com.length(); i++) {
            boolean[][][] nam = new boolean[maxDist * 2][nChange + 1][2];
            for (int j = 0; j < am.length; j++) {
                for (int k = 0; k <= nChange; k++) {
                    for (int l = 0; l < 2; l++) {
                        if (am[j][k][l]) {
                            if (com.charAt(i) == 'F') {
                                nam[j + (l == 0 ? 1 : -1)][k][l] = true;
                                if (k < nChange)
                                    nam[j][k + 1][1 - l] = true;
                            } else {
                                nam[j][k][1 - l] = true;
                                if (k < nChange)
                                    nam[j + (l == 0 ? 1 : -1)][k + 1][l] = true;
                            }
                        }
                    }
                }
            }
            am = nam;
        }

        int ans = 0;
        for (int j = 0; j < am.length; j++) {
            for (int k = 0; k <= nChange; k++) {
                for (int l = 0; l < 2; l++) {
                    if (am[j][k][l] && (k % 2 == nChange % 2)) {
                        ans = Math.max(ans, Math.abs(j - maxDist));
                    }
                }
            }
        }

        writer.println(ans);
    }

    static public void main(String[] args) {
        new C().run();
    }
}

import java.io.*;
import java.math.*;
import java.util.*;

public class Main
{
    BufferedReader reader;
    FastScanner sc;

    String line;
    int n;

    void solve() throws Exception
    {
        line = reader.readLine();
        n = sc.nextInt();

        int[][] dpmax = new int[line.length() + 1][n + 1];
        int[][] dpmin = new int[line.length() + 1][n + 1];

        for (int i = 0; i <= n; i++)
        {
            dpmax[line.length()][i] = dpmin[line.length()][i] = 0;
        }

        for (int i = line.length() - 1; i >= 0; i--)
        {
            if (line.charAt(i) == 'F')
            {
                dpmax[i][0] = dpmax[i + 1][0] + 1;
                dpmin[i][0] = dpmin[i + 1][0] + 1;
            }
            else
            {
                dpmax[i][0] = -dpmin[i + 1][0];
                dpmin[i][0] = -dpmax[i + 1][0];
            }
        }

        for (int i = line.length() - 1; i >= 0; i--)
        {
            for (int j = 1; j <= n; j++)
            {
                if (line.charAt(i) == 'F')
                {
                    dpmax[i][j] = Math.max(j <= line.length() - (i + 1) ? dpmax[i + 1][j] + 1 : 0, -dpmin[i + 1][j - 1]);
                    dpmin[i][j] = Math.min(j <= line.length() - (i + 1) ? dpmin[i + 1][j] + 1 : 0, -dpmax[i + 1][j - 1]);
                }
                else
                {
                    dpmax[i][j] = Math.max(j <= line.length() - (i + 1) ? -dpmin[i + 1][j] : 0, dpmax[i + 1][j - 1] + 1);
                    dpmin[i][j] = Math.min(j <= line.length() - (i + 1) ? -dpmax[i + 1][j] : 0, dpmin[i + 1][j - 1] + 1);
                }
            }
        }

        int answer = 0;

        for (int i = n; i >= 0; i -= 2)
        {
            if (Math.abs(dpmax[0][i]) > answer)
            {
                answer = Math.abs(dpmax[0][i]);
            }
            if (Math.abs(dpmin[0][i]) > answer)
            {
                answer = Math.abs(dpmin[0][i]);
            }
        }

        System.out.println(answer);
    }

    public static void main(String[] args) throws Exception
    {
        new Main().solve();
    }

    Main() throws Exception
    {
        if (System.getProperty("ONLINE_JUDGE") == null)
        {
            //System.setIn(new FileInputStream("input.txt"));
            //System.setOut(new PrintStream("output.txt"));
        }

        reader = new BufferedReader(new InputStreamReader(System.in));
        sc = new FastScanner(reader);
    }
}

class FastScanner
{
    BufferedReader reader;
    StringTokenizer strTok;

    public FastScanner(BufferedReader reader)
    {
        this.reader = reader;
    }

    public String nextToken() throws IOException
    {
        if (strTok == null || !strTok.hasMoreTokens())
        {
            strTok = new StringTokenizer(reader.readLine());
        }
        return strTok.nextToken();
    }

    public int nextInt() throws IOException
    {
        return Integer.parseInt(nextToken());
    }

    public long nextLong() throws IOException
    {
        return Long.parseLong(nextToken());
    }

    public double nextDouble() throws IOException
    {
        return Double.parseDouble(nextToken());
    }

    public BigInteger nextBigInteger() throws IOException
    {
        return new BigInteger(nextToken());
    }

    public BigDecimal nextBigDecimal() throws IOException
    {
        return new BigDecimal(nextToken());
    }
}

import java.util.Arrays;
import java.util.Scanner;

public class Logo_Turtle {
	static Scanner scan = new Scanner(System.in);
	static int n;
	static String s;
	static int[][][] Dp;
	static int Dist[][];

	static int max(int a, int b) {
		return (a > b) ? a : b;
	}

	static int solve(int index, int count, int i) {

		if (index == s.length() && count > 0) {
			return -1111111111;
		} else if (index == s.length()) {
			return 0;
		}
		if (Dp[index][count][i] != 987456) {
			return Dp[index][count][i];
		}
		int max = -1000000000;
		// change
		int change = 1;
		if (i == 0) {
			change = -1;
		}
		if (count - 1 >= 0) {
			if (s.charAt(index) == 'F') {
					max = max(max,solve(index + 1, count - 1, 1 - i));

			} else {

					max = max(max, change + solve(index + 1, count - 1, i));
			}
		}
		// Never Change
		if (s.charAt(index) == 'F') {
				max = max(max,change+ solve(index + 1, count, i) );
		} else {

				max = max(max, solve(index + 1, count, 1 - i));
		}

		return Dp[index][count][i] = max;

	}

	public static void main(String[] args) {
		s = scan.nextLine();
		n = scan.nextInt();
		Dist = new int[s.length() + 1][s.length() + 1];

		Dp = new int[s.length()][n + 1][2];
		for (int[][] row : Dp) {
			for (int[] y : row)
				Arrays.fill(y, 987456);
		}
int ans=0;
		for(int a=n;a>=0;a-=2){
			ans = Math.max(ans,solve(0,a,0));
			ans = Math.max(ans,solve(0,a,1));
		}
		System.out.println(ans);
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class C {
    static int[][][] DP;
    static String s;
    static int[] M = { 1, -1 };
    static int inf = 10000000;

    public static int get(int index, int com, int m) {
        if (com < 0)
            return -inf;
        if (index == s.length())
            if (com == 0)
                return 0;
            else
                return -inf;
        if (DP[index][com][m] != -1)
            return DP[index][com][m];
        if (s.charAt(index) == 'F') {
            int max = -inf;
            for (int i = 0; i <= com; i++) {
                if (i % 2 == 0)
                    max = Math.max(max, M[m] + get(index + 1, com - i, m));
                else
                    max = Math.max(max, get(index + 1, com - 1, 1 - m));
            }
            return DP[index][com][m] = max;
        } else {
            int max = -inf;
            for (int i = 0; i <= com; i++) {
                if (i % 2 == 0)
                    max = Math.max(max, get(index + 1, com, 1 - m));
                else
                    max = Math.max(max, M[m] + get(index + 1, com - 1, m));
            }
            return DP[index][com][m] = max;
        }

    }

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        s = in.readLine();
        int n = Integer.parseInt(in.readLine());
        DP = new int[s.length()][n + 1][2];
        for (int i = 0; i < DP.length; i++)
            for (int j = 0; j < DP[0].length; j++)
                DP[i][j][0] = DP[i][j][1] = -1;
        System.out.println(Math.max(get(0, n, 0), get(0, n, 1)));
    }
}

/**
 * Created by ckboss on 14-9-3.
 */
import java.util.*;

public class O {

    static int len,n;
    static int[][][][] dp= new int[2][200][500][100]; ///base is 200;
    static boolean[][][][] vis = new boolean[2][200][500][100];
    static String cmd;

    static int dfs(int dir,int cd,int pos,int cur)
    {

        if(cur<0) return 0;
        if(cd==len)
        {
            if(cur>0) return 0;
            else return Math.abs(pos-200);
        }

        if(vis[dir][cd][pos][cur]==true)
            return dp[dir][cd][pos][cur];
        int ret=0;

       // System.out.println("dir "+dir+" cd: "+cd+" pos: "+pos+" cur "+cur);

        int mv=(dir==1)?-1:1;

        if(cmd.charAt(cd)=='T')
            ret=Math.max(ret,Math.max(dfs(1^dir,cd+1,pos,cur),dfs(dir,cd+1,pos+mv,cur-1)));
        else if(cmd.charAt(cd)=='F')
            ret=Math.max(ret,Math.max(dfs(dir,cd+1,pos+mv,cur),dfs(1^dir,cd+1,pos,cur-1)));

        vis[dir][cd][pos][cur]=true;
        dp[dir][cd][pos][cur]=ret;

        return ret;
    }

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);

        cmd=in.nextLine();
        len=cmd.length();

        n=in.nextInt();

        int ans=-999999;
        for(int i=n;i>=0;i-=2)
        {
            ans=Math.max(ans,dfs(0,0,200,i));
        }

        System.out.println(ans);
    }
}
/*
FTFTFTFFFFTFTFTTTTTTFFTTTTFFTFFFTFTFTFFTFTFTFFFTTTFTTFTTTTTFFFFTTT
12
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;

public class E133 {
	BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
	StringTokenizer st = null;

	private void solution() throws IOException {
		String s = nextToken();
		int n = nextInt();
		int nap[] = new int[2];
		nap[0] = -1;
		nap[1] = 1;
		int dp[][][] = new int[s.length() + 1][n + 1][2];
		for (int i = 0; i <= s.length(); i++) {
			for (int j = 0; j <= n; j++) {
				for (int k = 0; k < 2; k++) {
					dp[i][j][k] = -100;
				}
			}
		}
		dp[0][0][0] = dp[0][0][1] = 0;
		for (int i = 1; i <= s.length(); i++) {
			for (int j = 0; j <= n; j++) {
				for (int k = 0; k < 2; k++) {
					if (s.charAt(i - 1) == 'F') {
						dp[i][j][k] = Math.max(dp[i][j][k], dp[i - 1][j][k]
								+ nap[k]);
						if (j > 0) {
							dp[i][j][k] = Math.max(dp[i][j][k],
									dp[i - 1][j - 1][1 - k]);
						}
					} else {
						if (j > 0) {
							dp[i][j][k] = Math.max(dp[i][j][k],
									dp[i - 1][j - 1][k] + nap[k]);
						}
						dp[i][j][k] = Math
								.max(dp[i][j][k], dp[i - 1][j][1 - k]);
					}
				}
			}
		}
		int ans = 0;
		for (int j = 0; j <= n; j++) {
			if (j % 2 != n % 2)
				continue;
			for (int k = 0; k < 2; k++) {
				ans = Math.max(ans, dp[s.length()][j][k]);
			}
		}
		System.out.println(ans);
	}

	String nextToken() throws IOException {
		if (st == null || !st.hasMoreTokens()) {
			st = new StringTokenizer(bf.readLine());
		}
		return st.nextToken();
	}

	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}

	public void print(int a[]) {
		for (int i = 0; i < a.length; i++) {
			System.out.print(a[i] + " ");
		}
	}

	public static void main(String args[]) throws IOException {
		new E133().solution();
	}
}

import java.util.Arrays;
import java.util.Scanner;

public class CF132C {
	private static final int INF = -125000;
	private static String commands;
	private static int[][][] memo;
	public static void main(String[] args) throws Exception {
		Scanner br = new Scanner(System.in);
		commands = br.next();
		int k = br.nextInt();

		memo = new int[commands.length()][k + 1][2];
		for (int i = 0; i < memo.length; i++) {
			for (int j = 0; j < memo[i].length; j++) {
				Arrays.fill(memo[i][j], INF);
			}
		}

		System.out.println(Math.max(go(0, k, 0), go(0, k, 1)));
	}

	private static int go(int index, int k, int direction) {
		if (k < 0) {
			return INF;
		}

		if (index >= commands.length()) {
			if (k > 0) {
				return INF;
			}

			return 0;
		}

		if (memo[index][k][direction] != INF) {
			return memo[index][k][direction];
		}

		int max = INF;
		for (int i = 0; i <= k; i++) {
			int newDirection, distance;
			if (i % 2 == 0) {
				newDirection = commands.charAt(index) == 'T' ? 1 - direction : direction;
				distance = commands.charAt(index) == 'T' ? 0 : 1;
			} else {
				newDirection = commands.charAt(index) == 'T' ? direction : 1 - direction;
				distance = commands.charAt(index) == 'T' ? 1 : 0;
			}

			if (direction == 1) {
				distance = -distance;
			}

			max = Math.max(max, go(index + 1, k - i, newDirection) + distance);
		}

		return memo[index][k][direction] = max;
	}
}

/*

FT
1

FFFTFFF
7

FFFF
0

TTTT
0

FTFTFTFTFTFTFTFTFTFT
1

 */

import java.io.*;

import java.awt.geom.Point2D;
import java.text.*;
import java.math.*;
import java.util.*;

public class Main implements Runnable {

	final String filename = "";

	public void solve() throws Exception {
		String comm = readword();
		int n = iread();
		int[][][] d = new int[2][2][n + 1];
		int INF = -1;
		int step = 0;
		Arrays.fill(d[0][0], -1);
		Arrays.fill(d[0][1], -1);
		d[0][1][0] = 0;
		for (int i = 0; i < comm.length(); i++) {
			Arrays.fill(d[step ^ 1][0], -1);
			Arrays.fill(d[step ^ 1][1], -1);
			for (int k = 0; k <= n; k++) {
				for (int j = 0; j < 2; j++) {
					int t = d[step][j][k];
					if (t != INF) {
						if (k + 2 <= n) {
							d[step][j][k + 2] = Math.max(d[step][j][k + 2], t);
						}
						int k1 = k;
						if (comm.charAt(i) != 'F')
							k1++;
						if (k1 <= n) {
							int j1 = j;
							if (t == 0)
								j1 = 1;
							int dx = (j1 * 2) - 1;
							int t1 = t + dx;
							d[step ^ 1][j1][k1] = Math.max(d[step ^ 1][j1][k1], t1);
						}

						k1 = k;
						if (comm.charAt(i) != 'T')
							k1++;
						if (k1 <= n) {
							int j1 = j ^ 1;
							int t1 = t;
							d[step ^ 1][j1][k1] = Math.max(d[step ^ 1][j1][k1], t1);
						}
					}
				}
			}
			step ^= 1;
		}
		int ans = Math.max(d[step][0][n], d[step][1][n]);
		out.write(ans + "\n");
	}

	public void run() {
		try {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new BufferedWriter(new OutputStreamWriter(System.out));
			// in = new BufferedReader(new FileReader(filename+".in"));
			// out = new BufferedWriter(new FileWriter(filename+".out"));
			solve();
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	public int iread() throws Exception {
		return Integer.parseInt(readword());
	}

	public double dread() throws Exception {
		return Double.parseDouble(readword());
	}

	public long lread() throws Exception {
		return Long.parseLong(readword());
	}

	BufferedReader in;

	BufferedWriter out;

	public String readword() throws IOException {
		StringBuilder b = new StringBuilder();
		int c;
		c = in.read();
		while (c >= 0 && c <= ' ')
			c = in.read();
		if (c < 0)
			return "";
		while (c > ' ') {
			b.append((char) c);
			c = in.read();
		}
		return b.toString();
	}

	public static void main(String[] args) {
		try {
			Locale.setDefault(Locale.US);
		} catch (Exception e) {

		}
		// new Thread(new Main()).start();
		new Thread(null, new Main(), "1", 1 << 25).start();
	}
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.util.*;
import java.lang.*;

/**
 *
 * @author Bryan AW
 */
public class Codeforces {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args){

        //Logo Turtle

        Scanner sc=new Scanner(System.in);

        String s=sc.next();

        int len=s.length();

        int n=sc.nextInt();

        int t=0;

        for (char c : s.toCharArray()){
            if (c=='T'){
                t++;
            }
        }

        int ans;

        if (n==t){
            ans=len;
        }
        else if (n>t){
            int left=n-t;
            ans=len-left%2;
        }
        else {
            int[][][] dp=new int[len+1][n+1][2];
            for (int i=0;i<=len;i++){
                for (int j=0;j<=n;j++){
                    dp[i][j][0]=-999;
                    dp[i][j][1]=-999;
                }
            }
            dp[0][0][0]=0;
            dp[0][0][1]=0;
            for (int i=1;i<=len;i++){
                for (int j=0;j<=n;j++){
                    for (int k=0;k<=j;k++){
                        if (s.charAt(i-1)=='F'){
                            if (k%2==0){
                                dp[i][j][0]=Math.max(dp[i][j][0], dp[i-1][j-k][0]+1);
                                dp[i][j][1]=Math.max(dp[i][j][1], dp[i-1][j-k][1]-1);
                            }
                            else {
                                dp[i][j][0]=Math.max(dp[i][j][0], dp[i-1][j-k][1]);
                                dp[i][j][1]=Math.max(dp[i][j][1], dp[i-1][j-k][0]);
                            }
                        }
                        else {
                            if (k%2==0){
                                dp[i][j][0]=Math.max(dp[i][j][0], dp[i-1][j-k][1]);
                                dp[i][j][1]=Math.max(dp[i][j][1], dp[i-1][j-k][0]);
                            }
                            else {
                                dp[i][j][0]=Math.max(dp[i][j][0], dp[i-1][j-k][0]+1);
                                dp[i][j][1]=Math.max(dp[i][j][1], dp[i-1][j-k][1]-1);
                            }
                        }
                    }
                }
            }
            ans=Math.max(dp[len][n][0], dp[len][n][1]);
        }

        System.out.println(ans);

    }

}

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    static char[] a;
    public static void main(String[] args) {
        Scanner r = new Scanner(System.in);

        a = r.next().toCharArray();
        int n = r.nextInt();

        for(int[][][][] l: dp)
        for(int[][][] i : l)
        for(int[][] j : i)
        for(int[] k : j)
            Arrays.fill(k, -1);

        int max = go(0, n, 0, 1, 0);

        System.out.println(max);
    }

    static int off = 102;
    static int[][][][][] dp = new int[101][51][210][3][2];
    private static int go(int i, int rem, int pos, int dir, int c) {
        if(i == a.length){
            if(rem == 0)return Math.abs(pos);
            else return 0;
        }
        if(dp[i][rem][pos + off][dir + 1][c] != -1)return dp[i][rem][pos + off][dir + 1][c];

        int w1 = 0, w2 = 0;
        if(!(a[i] == 'F' ^ c == 0)){
            w1 = go(i+1, rem, pos + dir, dir, 0);
            if(rem-1 >= 0)w2 = go(i, rem-1, pos, dir, 1-c);

            return dp[i][rem][pos + off][dir + 1][c] = Math.max(w1, w2);
        }else{
            w1 = go(i+1, rem, pos, -dir, 0);
            if(rem-1 >= 0)w2 = go(i, rem-1, pos, dir, 1-c);

            return dp[i][rem][pos + off][dir + 1][c] = Math.max(w1, w2);
        }
    }
}

import java.util.Arrays;
import java.util.Scanner;

public class F {
    static int[][][][] dp = new int[110][230][110][3];
    static String inp;

    public static int min(int index, int pos, int n, int direction) {
        if (index == inp.length() && n == 0)
            return Math.abs(pos);
        else if (index == inp.length())
            return Integer.MIN_VALUE;
        else if (dp[index][pos + 100][n][direction + 1] != -1)
            return dp[index][pos + 100][n][direction + 1];
        else {
            if (n == 0) {
                if (inp.charAt(index) == 'T') {
                    return dp[index][pos + 100][n][direction + 1] = min(
                            index + 1, pos, n, -direction);
                } else
                    return dp[index][pos + 100][n][direction + 1] = min(
                            index + 1, pos + direction, n, direction);
            }

            else {
                if (inp.charAt(index) == 'T') {
                    int max = min(index + 1, pos, n, -direction);
                    for (int i = 1; i <= n; i++) {
                        if (i % 2 == 0) {
                            max = Math.max(max,
                                    min(index + 1, pos, n - i, -direction));
                        } else {
                            max = Math.max(
                                    min(index + 1, pos + direction, n - i,
                                            direction), max);
                        }
                    }
                    return dp[index][pos + 100][n][direction + 1] = max;

                } else {
                    int max = min(index + 1, pos + direction, n, direction);
                    for (int i = 1; i <= n; i++) {
                        if (i % 2 == 0) {
                            max = Math.max(
                                    max,
                                    min(index + 1, pos + direction, n - i,
                                            direction));
                        } else {
                            max = Math.max(max,
                                    min(index + 1, pos, n - i, -direction));
                        }
                    }
                    return dp[index][pos + 100][n][direction + 1] = max;
                }
            }
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        inp = in.nextLine();

        int n = in.nextInt();
        for (int i = 0; i < dp.length; i++)
            for (int j = 0; j < dp[i].length; j++)
                for (int k = 0; k < dp[i][j].length; k++)
                    Arrays.fill(dp[i][j][k], -1);
        System.out.println(min(0, 0, n, 1));
    }
}

import java.util.Scanner;

public class LogoTurtle {
	int [][][] dp;
	boolean [][][] visited;
	String s;

	public LogoTurtle(int[][][] dp, boolean[][][] visited, String s) {
		super();
		this.dp = dp;
		this.visited = visited;
		this.s = s;
	}
	int score(String s,boolean f) {
		int ans = 0;
		for (int i = 0; i < s.length(); i++) {
			if(s.charAt(i) == 'F') {
				if(f) {
					ans ++ ;
				}else {
					ans -- ;
				}
			}else {
				f=!f;
			}
		}
		return Math.abs(ans);
	}
	int solve(int idx,int rem,int score, boolean f) {
		if(idx == s.length() && rem != 0) {
			return Integer.MIN_VALUE;
		}
		if(idx == s.length() && rem == 0) {
			return score;
		}
		if (rem < 0) {
			return Integer.MIN_VALUE;
		}
		if (visited[idx][rem][score] ) {
			return dp[idx][rem][score];
		}
		visited[idx][rem][score] = true;
		if(rem == 0) {

			dp[idx][rem][score] =score + score(s.substring(idx, s.length()),f);
			return dp[idx][rem][score];
		}

		int y ,z;
		if(s.charAt(idx) == 'T') {

			 y = solve(idx , rem - 1, score, f);
		}else {

			 y = solve(idx , rem - 1, score, !f);
		}
		if(s.charAt(idx) == 'F') {

			 z = solve(idx + 1, rem , f?score +1 : Math.abs(score - 1), f);
		}else {

			 z = solve(idx + 1, rem , score, !f);
		}
		dp[idx][rem][score] = Math.max(y, z);
		return dp[idx][rem][score];
	}
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String s = in.nextLine();
		int n = in.nextInt();
		LogoTurtle x = new LogoTurtle(new int [s.length()][n + 1][101], new boolean [s.length()][n + 1][101],s);
		System.out.println(x.solve(0, n, 0, true));
	}

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;

public class E133 {
	BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
	StringTokenizer st = null;

	private void solution() throws IOException {
		String s = nextToken();
		int n = nextInt();
		int nap[] = new int[2];
		nap[0] = -1;
		nap[1] = 1;
		int dp[][][] = new int[200][100][2];
		for (int i = 0; i < 200; i++) {
			for (int j = 0; j < 100; j++) {
				for (int k = 0; k < 2; k++) {
					dp[i][j][k] = -1;
				}
			}
		}
		dp[0][0][0] = dp[0][0][1] = 0;
		for (int i = 1; i <= s.length(); i++) {
			for (int j = 0; j <= n; j++) {
				for (int k = 0; k < 2; k++) {
					if (s.charAt(i-1) == 'F') {
						dp[i][j][k] = Math.max(dp[i][j][k], dp[i - 1][j][k]
								+ nap[k]);
						if (j > 0) {
							dp[i][j][k] = Math.max(dp[i][j][k],
									dp[i - 1][j - 1][1 - k]);
						}
					} else if (s.charAt(i-1) == 'T') {
						if (j > 0) {
							dp[i][j][k] = Math.max(dp[i][j][k],
									dp[i - 1][j - 1][k] + nap[k]);
						}
						dp[i][j][k] = Math
								.max(dp[i][j][k], dp[i - 1][j][1 - k]);
					}
				}
			}
		}
		int ans = 0;
		for (int j = 0; j <= n; j++) {
			if (j % 2 != n % 2)
				continue;
			for (int k = 0; k < 2; k++) {
				ans = Math.max(ans, dp[s.length()][j][k]);
			}
		}
		System.out.println(ans );
	}

	String nextToken() throws IOException {
		if (st == null || !st.hasMoreTokens()) {
			st = new StringTokenizer(bf.readLine());
		}
		return st.nextToken();
	}

	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}

	public void print(int a[]) {
		for (int i = 0; i < a.length; i++) {
			System.out.print(a[i] + " ");
		}
	}

	public static void main(String args[]) throws IOException {
		new E133().solution();
	}
}

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

/**
 *
 * @author quangpham
 */
public class E {

    private static final int[] delta = new int[]{+1, -1};

    private class Where {

        public int processed, changed, position, direction;

        public Where(int processed, int changed, int position, int direction) {
            this.processed = processed;
            this.changed = changed;
            this.position = position;
            this.direction = direction;
        }
    }

    public void run() {
        Scanner scanner = new Scanner(System.in);

        String s = scanner.next();
        int nchange = scanner.nextInt();

        int result = 0;

        int ncommand = s.length();
        boolean[][][][] reached = new boolean[ncommand + 1][nchange + 1][205][2];

        for (int i = 0; i <= ncommand; ++i) {
            for (int j = 0; j <= nchange; ++j) {
                for (int x = 0; x < 205; ++x) {
                    reached[i][j][x][0] = reached[i][j][x][1] = false;
                }
            }
        }

        reached[0][0][100][0] = true;

        Queue<Where> queue = new LinkedList<Where>();
        queue.add(new Where(0, 0, 100, 0));

        while (!queue.isEmpty()) {
            Where current = queue.poll();

            int p = current.processed;
            int c = current.changed;
            int x = current.position;
            int d = current.direction;

            if (c == nchange) {
                result = Math.max(result, Math.abs(x - 100));
            }

            if (p == ncommand) {
                continue;
            }

            if (s.charAt(p) == 'F') {
                Where next = new Where(p + 1, c, x + delta[d], d);
                if (!reached[next.processed][next.changed][next.position][next.direction]) {
                    reached[next.processed][next.changed][next.position][next.direction] = true;
                    queue.add(next);
                }

                if (c < nchange) {
                    next = new Where(p + 1, c + 1, x, 1 - d);
                    if (!reached[next.processed][next.changed][next.position][next.direction]) {
                        reached[next.processed][next.changed][next.position][next.direction] = true;
                        queue.add(next);
                    }
                }
            } else {
                Where next = new Where(p + 1, c, x, 1 - d);
                if (!reached[next.processed][next.changed][next.position][next.direction]) {
                    reached[next.processed][next.changed][next.position][next.direction] = true;
                    queue.add(next);
                }

                if (c < nchange) {
                    next = new Where(p + 1, c + 1, x + delta[d], d);
                    if (!reached[next.processed][next.changed][next.position][next.direction]) {
                        reached[next.processed][next.changed][next.position][next.direction] = true;
                        queue.add(next);
                    }
                }
            }
        }

        System.out.println(result);

        scanner.close();
    }

    public static void main(String[] args) {
        new E().run();
    }
}

import java.util.Arrays;
import java.util.Scanner;

public class C {
    static String s;
    static int[][][] dp;

    public static int solve(int idx, int rem, int dir) {
        if (rem == 0) {
            int res = 0;
            for (int i = idx; i < s.length() && i >= 0; i++) {
                if (s.charAt(i) == 'T') {
                    dir = dir * -1;
                } else {
                    res += dir;
                    res = Math.max(res, 0);
                }
            }
            return res;
        }
        if (idx == s.length()) {
            return -10000000;
        }
        if (dp[idx][rem][dir + 1] != -1)
            return dp[idx][rem][dir + 1];
        int max = 0;
        for (int i = 0; i <= rem; i++) {
            if (s.charAt(idx) == 'F') {
                if (i % 2 == 0) {
                    max = Math.max(max, 1 + solve(idx + 1, rem - i, dir));
                } else {
                    max = Math.max(max, solve(idx + 1, rem - i, dir * -1));
                }
            } else {
                if (i % 2 == 0) {
                    max = Math.max(max, solve(idx + 1, rem - i, dir * -1));
                } else {
                    max = Math.max(max, 1 + solve(idx + 1, rem - i, dir));
                }
            }
        }
        return dp[idx][rem][dir + 1] = max;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        s = sc.next();
        int n = sc.nextInt();
        dp = new int[s.length()][n + 1][3];
        for (int i = 0; i < s.length(); i++) {
            for (int j = 0; j <= n; j++)
                Arrays.fill(dp[i][j], -1);
        }
        System.out.println(solve(0, n, 1));
    }
}

import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.image.AreaAveragingScaleFilter;
import static java.lang.Math.*;
import java.lang.*;

public class Main {
    static FastScanner in;
    static PrintWriter out;
    public static void main(String[] args) throws FileNotFoundException {
        runIO(0);

        Task solver = new Task();
        solver.solve(1, in, out);
        out.close();
    }

    public static void runIO(int R) throws FileNotFoundException{
        if (R==1){
            in = new FastScanner(new File("input.txt"));
            out = new PrintWriter(new File("output.txt"));
        } else
        {
            in = new FastScanner(System.in);
            out = new PrintWriter(System.out);
        }
    }
}

class Task {
    final int N = 110;
    final int Inf = 1000000007;
    String S;
    int n;
    int B=0, aa=0;
    int m;
    int dp[][][] = new int[N][52][2];
    int best=0;
    //Time Complexity must be O(N*N*M*2) ~ O(N*N*N)
    public int calc(int pos, int remain, int s, PrintWriter out) {
        if (remain < 0) return -1000000000;
        if (pos == n && remain > 0) return -1000000000;
        if (pos == n && remain == 0) return 0;

        if (dp[pos][remain][s]>0) return dp[pos][remain][s]-1;
        char c = S.charAt(pos);

        int p=0;
        if (c=='F'){
            if (s==1) p = max(p, calc(pos+1, remain, s ,out)-1); else
                p = max(p, calc(pos+1, remain, s, out)+1);
        } else
        {
            p = max(p, calc(pos+1, remain, s, out));
        }
        if (remain>0) {
            if (c == 'F') {
                p = max(p, calc(pos + 1, remain - 1, s ^ 1, out));
            } else {
                if (s == 1) p = max(p, calc(pos + 1, remain - 1, s ^ 1, out)-1);
                else
                    p = max(p, calc(pos + 1, remain - 1, s ^ 1, out)+1);
            }
        }
        //out.println(pos+" "+len+" "+remain+" "+s+" = "+p);
        p++;
        dp[pos][remain][s]=p;
        return p-1;
    }

    public void solve(int testNumber, FastScanner in, PrintWriter out) {
        S = in.next();
        n = S.length();
        m = in.nextInt();
        boolean existsT = false;

        for (int i=1; i<=n; i++){
            char c = S.charAt(i-1);
            //for (int j)
            if (c=='T') existsT = true;
        }
        if (existsT==false) out.println(S.length()); else {
            int ans = calc(0, m, 0, out);
            out.println(ans);
        }

    }

}

class Pair implements Comparable<Pair>{
    public int first, second;
    Pair(){
        first=second=-1;
    }
    Pair(int a, int b){
        first = a; second=b;
    }
    @Override
    public int compareTo(Pair b){
        if (first<b.first) return 1; else
        if (first>b.first) return -1; else
        if (second<b.second)  return 1; else return -1;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        char c = (char)42;
        result = (int)(1L*first*second + first + second);
        if (second!=0) result+=first % second;
        if (first!=0) result+=second%first;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        Pair b = (Pair)obj;
        if (first==b.first && second==b.second) return true;
        return false;
    }

}

class PairComparator implements Comparator<Pair>{

    public int compare(Pair a, Pair b) {
        if (a.first<b.first) return 1; else
        if (a.first>b.first) return -1; else
        if (a.second<b.second)  return 1; else return -1;
    }
}

class FastScanner {
    BufferedReader br;
    StringTokenizer st;

    public FastScanner(File f) {
        try {
            br = new BufferedReader(new FileReader(f));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public FastScanner(InputStream f) {
        br = new BufferedReader(new InputStreamReader(f));
    }

    String next() {
        while (st == null || !st.hasMoreTokens()) {
            String s = null;
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (s == null)
                return null;
            st = new StringTokenizer(s);
        }
        return st.nextToken();
    }

    boolean hasMoreTokens() {
        while (st == null || !st.hasMoreTokens()) {
            String s = null;
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (s == null)
                return false;
            st = new StringTokenizer(s);
        }
        return true;
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }
}

import java.util.Scanner;

public class LogoTurtle {

	static String l;
	static int[][][][] dp;

	public static int dfs(int i, int n, int p, int d) {

		if (n == 0) {
			for (int j = i + 1; j < l.length(); j++) {
				if (l.charAt(j) == 'F') p += d;
				else d *= -1;
			}
			return p;
		}
		if (i >= l.length()) return Integer.MIN_VALUE;

		if (dp[i][n][100 + p][d == 1 ? 0 : 1] != -201)
			return dp[i][n][100 + p][d == 1 ? 0 : 1];

		int max = 0;
		int dtemp  = d;
		for (int j = 0; j <= n; j++) {
			char s = l.charAt(i);

			if (j % 2 != 0) {
				s = (s == 'F') ? 'T' : 'F';
			}
			if (s == 'F') p += d;
			if (s == 'T') dtemp = -d;

			max = Math.max(max, dfs(i + 1, n - j, p, dtemp));
		}
		return max;
	}

	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);

		l = scan.nextLine();
		int n = Integer.parseInt(scan.nextLine());

		dp = new int[l.length()][n + 1][201][2];

		for (int i = 0; i < l.length(); i++) {
			for (int j = 0; j < n + 1; j++) {
				for (int j2 = 0; j2 < 201; j2++) {
					for (int k = 0; k < 2; k++) {
						dp[i][j][j2][k] = -201;
					}
				}
			}
		}

		System.out.println(dfs(0, n, 0, l.charAt(0) == 'F' ? 1 : -1));

	}

}

import java.util.Scanner;

public class CF133E {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String commands = sc.next();
        int n = sc.nextInt();

        State[][][] dp = new State[commands.length()+1][n+1][4];
        State init = State.valueOf(0, 0, Direction.LEFT);
        dp[0][0][0] = init;
        for (int i = 1; i < dp.length; i++) {
            boolean commandIsT = commands.charAt(i-1) == 'T';
            for (int j = 0; j < 4; j++) {
                if(dp[i-1][0][(commandIsT ? j+1 : j) % 4] != null) {
                    dp[i][0][j] = dp[i-1][0][(commandIsT ? j+1 : j) % 4].command(commandIsT);
                }
            }
            for (int j = 1; j < n+1; j++) {
                for (int k = 0; k < 4; k++) {
                    State fromLeft = null;
                    State fromTopLeft = null;
                    State fromTop = j > 1 ? dp[i][j-2][k] : null;
                    if (commandIsT) {
                        if(dp[i-1][j][(k-1+4)%4] != null) fromLeft = dp[i-1][j][(k-1+4)%4].turnAround();
                        if(dp[i-1][j-1][k] != null) fromTopLeft = dp[i-1][j-1][k].forward();
                    }
                    else {
                        if(dp[i-1][j][k] != null) fromLeft = dp[i-1][j][k].forward();
                        if(dp[i-1][j-1][(k-1+4)%4] != null) fromTopLeft = dp[i-1][j-1][(k-1+4)%4].turnAround();
                    }
                    dp[i][j][k] = State.getBigger(fromLeft, State.getBigger(fromTopLeft, fromTop));
                }
            }
        }
        int max = 0;
        for (int i = 0; i < 4; i++) {
            if(dp[commands.length()][n][i] != null)
                max = Math.max(max, dp[commands.length()][n][i].dist);
        }
        System.out.println(max);
    }

    enum Direction {
        LEFT(-1,0), UP(0,-1), RIGHT(1,0), DOWN(0,1);

        private Direction(int x, int y) {
            dx = x;
            dy = y;
        }
        int dx,dy;
    }

    static class State {
        final int x;
        final int y;
        final Direction dir;
        final int dist;
        public State(int x, int y, Direction dir) {
            this.x = x;
            this.y = y;
            this.dir = dir;
            dist = Math.abs(x) + Math.abs(y);
        }
        static State valueOf(int x, int y, Direction dir) {
            return new State(x, y, dir);
        }
        State forward() {
            return valueOf(x + dir.dx, y + dir.dy, dir);
        }
        State turnAround() {
            if (valuesTemp == null) {
                valuesTemp = Direction.values();
            }
            return valueOf(x, y, valuesTemp[(dir.ordinal() + 1) % valuesTemp.length]);
        }
        static Direction[] valuesTemp;
        State command(boolean c) {
            return c ? turnAround() : forward();
        }

        static State getBigger(State a, State b) {
            if (a == null) return b;
            if (b == null) return a;
            return a.dist > b.dist ? a : b;
        }

    }

}

import java.util.*;
public class C {
	static int [] reverse = new int [257];
	static int [][][] dp = new int [105][105][2];
	static char [] path;
	static int MIN_VAL = -(1<<20);
	public static void main (String [] arg) {
		Scanner sc = new Scanner(System.in);
		path = sc.next().toCharArray();
		int n = sc.nextInt();

		for (int i = 0; i<dp.length; ++i) for (int j = 0; j<dp[0].length; ++j) Arrays.fill(dp[i][j], MIN_VAL);
		int ans = recurse(n, 0, 1);
		System.out.println(ans);
	}
	public static int recurse(int n, int pos, int orientation) {
		//System.err.println("@ " + n + " , " + pos + " , " + orientation);
		if (dp[n][pos][orientation] > MIN_VAL) return dp[n][pos][orientation];
		if (pos >= path.length) return ( n%2 == 0) ? 0 : MIN_VAL;
		int dir = (orientation == 0) ? -1 : 1;

		int best = MIN_VAL;
		if (n != 0) {
			if (path[pos] == 'F') best = Math.max(best, recurse(n-1, pos+1, 1-orientation));
			if (path[pos] == 'T') best = Math.max(best, dir + recurse(n-1, pos+1, orientation));
		}
		if (path[pos] == 'T') best = Math.max(best, recurse(n, pos+1, 1-orientation));
		if (path[pos] == 'F') best = Math.max(best, dir + recurse(n, pos+1, orientation));
		dp[n][pos][orientation] = best;
		return best;
	}

}

import java.io.*;
import java.util.Arrays;
import static java.lang.Integer.*;
public class E {
    static int [][][][] dp;
    static String info;
    //0 for forward, 1 for backward
    public static int runDP(int idx, int rem, int score, int dir){
        if(idx >= info.length() && rem == 0)
            return score;
        if(rem < 0)
            return -(int)1e9;
        if(idx >= info.length())
            return -(int)1e9;
        int accessScore = score < 0 ? score * -1 : score;
        if(dp[idx][rem][accessScore][dir] != -1)
            return dp[idx][rem][accessScore][dir];
        int ans = 0;
        //try executing current instruction i times from 0 to rem
        for(int i = 0 ; i <= rem ; ++i){
            if(info.charAt(idx) == 'T'){
                if(i % 2 == 0)
                    ans = Math.max(ans, runDP(idx + 1, rem - i, score, 1 - dir));
                else{
                    int nscore = dir == 0 ? score + 1 : score - 1;
                    ans = Math.max(ans, runDP(idx + 1, rem - i, nscore, dir));
                }
            }else{
                if(i % 2 == 0){
                    int nscore = dir == 0 ? score + 1 : score - 1;
                    ans = Math.max(ans, runDP(idx + 1, rem - i, nscore, dir));
                }else{
                    ans = Math.max(ans, runDP(idx + 1, rem - i, score, 1 - dir));
                }
            }
        }
        return dp[idx][rem][accessScore][dir] = ans;
    }
    public static void main(String[] args)throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String in = br.readLine();
        info = in;
        int K =parseInt(br.readLine());
        dp = new int [in.length() + 1][K + 1][105][2];
        for(int i = 0 ; i < dp.length ; ++i)
            for(int j = 0 ; j < dp[i].length ; ++j)
                for(int k = 0 ; k < dp[i][j].length ; ++k)
                    Arrays.fill(dp[i][j][k], -1);
        int ans = runDP(0, K, 0, 0);
        System.out.println(ans);
    }
}

import java.util.Scanner;

public class LogoTurtle {

	static String l;
	static int[][][][] dp;

	public static int dfs(int i, int n, int p, int d) {

		if (n == 0) {
			for (int j = i + 1; j < l.length(); j++) {
				if (l.charAt(j) == 'F')
					p += d;
				else
					d *= -1;
			}
			return p;
		}
		if (i >= l.length())
			return Integer.MIN_VALUE;

		if (dp[i][n][100 + p][d == 1 ? 0 : 1] != -201)
			return dp[i][n][100 + p][d == 1 ? 0 : 1];

		int max = 0;
		int dtemp = d;
		int ptemp = p;
		for (int j = 0; j <= n; j++) {
			dtemp = d;
			ptemp = p;
			char s = l.charAt(i);

			if (j % 2 != 0)
				s = (s == 'F') ? 'T' : 'F';
			if (s == 'F')
				ptemp += d;
			if (s == 'T')
				dtemp = -d;

			max = Math.max(max, dfs(i + 1, n - j, ptemp, dtemp));
		}

		dp[i][n][100 + p][d == 1 ? 0 : 1] = max;
		return max;
	}

	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);

		l = scan.nextLine();
		int n = Integer.parseInt(scan.nextLine());

		dp = new int[l.length()][n + 1][201][2];

		for (int i = 0; i < l.length(); i++) {
			for (int j = 0; j < n + 1; j++) {
				for (int j2 = 0; j2 < 201; j2++) {
					for (int k = 0; k < 2; k++) {
						dp[i][j][j2][k] = -201;
					}
				}
			}
		}

		System.out.println(dfs(0, n, 0, l.charAt(0) == 'F' ? 1 : -1));

	}

}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class cf132c {
  static int n,m,oo=987654321;;
  static String v;
  static Integer[][][] memo;
  public static void main(String[] args) {
    FastIO in = new FastIO(), out = in;
    v = in.next().trim();
    n = in.nextInt();
    m = v.length();
    memo = new Integer[2][m][n+1];
    out.println(Math.max(go(0,n,0),go(0,n,1)));
    out.close();
  }
  static int go(int pos, int left, int dir) {
    if(left < 0) return -oo;
    if(pos == m) {
      return left==0?0:-oo;
    }
    if(memo[dir][pos][left] != null)
      return memo[dir][pos][left];
    int ans = -oo;
    char comm = v.charAt(pos);
    ans = Math.max(ans, go(pos+1,left-(comm=='T'?0:1),1-dir));
    ans = Math.max(ans, 2*dir-1 + go(pos+1,left-(comm=='F'?0:1),dir));
    return memo[dir][pos][left] = ans;
  }
  static class FastIO extends PrintWriter {
    BufferedReader br;
    StringTokenizer st;

    public FastIO() {
      this(System.in,System.out);
    }
    public FastIO(InputStream in, OutputStream out) {
      super(new BufferedWriter(new OutputStreamWriter(out)));
      br = new BufferedReader(new InputStreamReader(in));
      scanLine();
    }
    public void scanLine() {
      try {
        st = new StringTokenizer(br.readLine().trim());
      } catch(Exception e) {
        throw new RuntimeException(e.getMessage());
      }
    }
    public int numTokens() {
      if(!st.hasMoreTokens()) {
        scanLine();
        return numTokens();
      }
      return st.countTokens();
    }
    public String next() {
      if(!st.hasMoreTokens()) {
        scanLine();
        return next();
      }
      return st.nextToken();
    }
    public double nextDouble() {
      return Double.parseDouble(next());
    }
    public long nextLong() {
      return Long.parseLong(next());
    }
    public int nextInt() {
      return Integer.parseInt(next());
    }
  }
}

import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;

public class P132C implements Runnable {

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

    public static void main(String[] args) {
        new Thread(null, new P132C(), "", 256 * (1L << 20)).start();
    }

    public void run() {
        try {
            long t1 = System.currentTimeMillis();
            if (System.getProperty("ONLINE_JUDGE") != null) {
                in = new BufferedReader(new InputStreamReader(System.in));
                out = new PrintWriter(System.out);
            } else {
                in = new BufferedReader(new FileReader("src/input.txt"));
                out = new PrintWriter("src/output.txt");
            }
            Locale.setDefault(Locale.US);
            solve();
            in.close();
            out.close();
            long t2 = System.currentTimeMillis();
            System.err.println("Time = " + (t2 - t1));
        } catch (Throwable t) {
            t.printStackTrace(System.err);
            System.exit(-1);
        }
    }

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            tok = new StringTokenizer(in.readLine());
        }
        return tok.nextToken();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }

    // solution
    void solve() throws IOException {
        String command = readString();
        int n = command.length();
        int k = readInt();
        int[][] fmin = new int[n + 1][k + 1], fmax = new int[n + 1][k + 1];
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= k; j++) {
                fmin[i][j] = Integer.MAX_VALUE / 2;
                fmax[i][j] = Integer.MIN_VALUE / 2;
            }
        }
        fmin[0][0] = 0;
        fmax[0][0] = 0;
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= k; j++) {
                if (command.charAt(i - 1) == 'F') {
                    fmax[i][j] = fmax[i - 1][j] + 1;
                    fmin[i][j] = fmin[i - 1][j] + 1;
                    if (j > 0) {
                        fmax[i][j] = Math.max(fmax[i][j], -fmin[i - 1][j - 1]);
                        fmin[i][j] = Math.min(fmin[i][j], -fmax[i - 1][j - 1]);
                    }
                } else {
                    fmax[i][j] = -fmin[i - 1][j];
                    fmin[i][j] = -fmax[i - 1][j];
                    if (j > 0) {
                        fmax[i][j] = Math.max(fmax[i][j], fmax[i - 1][j - 1] + 1);
                        fmin[i][j] = Math.min(fmin[i][j], fmin[i - 1][j - 1] + 1);
                    }
                }
            }
        }
        int max = Math.max(fmax[n][k], Math.abs(fmin[n][k]));
        for (int wasted = 1; k - 2 * wasted >= 0; wasted++) {
            max = Math.max(max, fmax[n][k - wasted * 2]);
            max = Math.max(max, Math.abs(fmin[n][k - wasted * 2]));
        }
        for (int wasted = 0; k - 2 * wasted - 1 >= 0; wasted++) {
            max = Math.max(max, fmax[n][k - 1 - wasted * 2] - 1);
            max = Math.max(max, Math.abs(fmin[n][k - 1 - wasted * 2]) - 1);
        }
        out.println(max);
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class R96D2_E {
    static String inp;
    static int n;
    static int st;
    static int DP[][][];

    public static int call(int i, int rem, int add) {
        if (i == n && rem == 0)
            return 0;
        if (i == n || rem<0)
            return -1000000;
        int d = add == -1 ? 1 : 0;

        if (DP[i][rem][d] != -1)
            return DP[i][rem][d];

        if (rem == 0) {
            if (inp.charAt(i) == 'F')
                return DP[i][rem][d] = add + call(i + 1, rem, add);
            else
                return DP[i][rem][d] = call(i + 1, rem, add * -1);
        } else {
            int res = 0;
            int res2 = 1;
            for (int j = 0; j <= rem; j++) {
                if ((inp.charAt(i) == 'F' && j % 2 == 0)
                        || (inp.charAt(i) == 'T' && j % 2 == 1)){
                    int y = add + call(i + 1, rem - j,  add);
                    if(y<10000 && y>-10000){
                    res = Math.max(res, Math.abs(y));
                    if(y<0)
                    res2 = -1;
                    else
                        res2 = 1;
                    }
                }else{
                    int y = call(i + 1, rem - j, -1 * add);
                    if(y<10000 && y>-10000){
                    res = Math.max(res, Math.abs(y));
                    if(y<0)
                        res2 = -1;
                    else
                        res2 = 1;
                    }
                }
            }
            return DP[i][rem][d] = res*res2;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        // int n = Integer.parseInt(in.readLine());
        // String []s = in.readLine().split(" ");
        inp = in.readLine();
        n = inp.length();
        st = Integer.parseInt(in.readLine());
        DP = new int[n][st + 1][2];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < st + 1; j++) {
                for (int k = 0; k < 2; k++) {
                    DP[i][j][k] = -1;
                }
            }

        }
        System.out.println(Math.abs(call(0,st,1)));
    }
}

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        int n = s.length();
        int[]a = new int[n+1];
        for (int i = 0; i < n; i++) {
            String t;
            if (i==0)
                t = "0";
            else
                t = Integer.toBinaryString(s.codePointAt(i-1));
            while (t.length()!=8)
                t = "0"+t;
            String rev = "";
            for (int j = 7; j >= 0; j--) {
                rev += t.charAt(j);
            }
            int k = Integer.valueOf(rev, 2);
            String t2;
            t2 = Integer.toBinaryString(s.codePointAt(i));
            while (t2.length()!=8)
                t2 = "0"+t2;
            String rev2 = "";
            for (int j = 7; j >= 0; j--) {
                rev2 += t2.charAt(j);
            }
            int k2 = Integer.valueOf(rev2, 2);
            a[i] = k-k2;
            if (a[i] < 0)
                a[i] += 256;
            System.out.println(a[i]);
        }
    }

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.StringTokenizer;

public class magic2 {
	static char[] input;
	static int[][][] memo;
	public static void main(String[] args) throws Exception {
		FasterScanner sc = new FasterScanner();
		PrintWriter out = new PrintWriter(System.out);
		input = sc.next().toCharArray();
		int N = sc.nextInt();
		memo = new int[input.length][2][N+1];
		for(int[][] x : memo)
			for(int[] y : x)
				Arrays.fill(y,987654321);
		out.println(DP(0,1,N));
		out.close();
	}

	private static int DP(int pos, int dir, int changes) {
		if(changes<0)return -987654;
		if(pos==input.length){
			if(changes==0)return 0;
			return -987654;
		}
		if(memo[pos][dir][changes]!=987654321)return memo[pos][dir][changes];
		int change = 1;
		if(dir==0)change = -1;
		int ans = 0;
		if(input[pos]=='F'){
			//forward
			ans=Math.max(ans,change+DP(pos+1,dir,changes));
			ans=Math.max(ans,DP(pos+1,Math.max(0,dir-1),changes-1));
		}
		else{
			//turn
			ans=Math.max(ans,DP(pos+1,Math.max(0,dir-1),changes));
			ans=Math.max(ans,change+DP(pos+1,dir,changes-1));
		}
		return memo[pos][dir][changes]=ans;
	}

	private static int fix(char c) {
		if(c=='S')return 0;
		return c-'a'+1;
	}

	static class FasterScanner{
		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;

		public FasterScanner(){
			stream = System.in;
		}
		int read(){
			if(numChars==-1)
				throw new InputMismatchException();
			if(curChar>=numChars){
				curChar = 0;
				try{
					numChars = stream.read(buf);
				} catch (IOException e){
					throw new InputMismatchException();
				}
				if(numChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		boolean isSpaceChar(int c){
			return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;
		}
		boolean isEndline(int c){
			return c=='\n'||c=='\r'||c==-1;
		}
		int nextInt(){
			return Integer.parseInt(next());
		}
		long nextLong(){
			return Long.parseLong(next());
		}
		double nextDouble(){
			return Double.parseDouble(next());
		}
		String next(){
			int c = read();
			while(isSpaceChar(c))
				c=read();
			StringBuilder res = new StringBuilder();
			do{
				res.appendCodePoint(c);
				c=read();
			} while(!isSpaceChar(c));
			return res.toString();
		}
		String nextLine(){
			int c = read();
			while(isEndline(c))
				c=read();
			StringBuilder res = new StringBuilder();
			do{
				res.appendCodePoint(c);
				c = read();
			}while(!isEndline(c));
			return res.toString();
		}

	}
	static class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		public FastScanner(InputStream in) throws Exception {
			br = new BufferedReader(new InputStreamReader(in));
			st = new StringTokenizer(br.readLine().trim());
		}

		public int numTokens() throws Exception {
			if (!st.hasMoreTokens()) {
				st = new StringTokenizer(br.readLine().trim());
				return numTokens();
			}
			return st.countTokens();
		}

		public boolean hasNext() throws Exception {
			if (!st.hasMoreTokens()) {
				st = new StringTokenizer(br.readLine().trim());
				return hasNext();
			}
			return true;
		}

		public String next() throws Exception {
			if (!st.hasMoreTokens()) {
				st = new StringTokenizer(br.readLine().trim());
				return next();
			}
			return st.nextToken();
		}

		public double nextDouble() throws Exception {
			return Double.parseDouble(next());
		}

		public float nextFloat() throws Exception {
			return Float.parseFloat(next());
		}

		public long nextLong() throws Exception {
			return Long.parseLong(next());
		}

		public int nextInt() throws Exception {
			return Integer.parseInt(next());
		}

		public String nextLine() throws Exception {
			return br.readLine();
		}
	}

}

import java.util.*;
public class C {
	static int [] reverse = new int [257];
	static int [][][] dp = new int [105][105][2];
	static char [] path;
	static int MIN_VAL = -(1<<20);
	public static void main (String [] arg) {
		Scanner sc = new Scanner(System.in);
		path = sc.next().toCharArray();
		int n = sc.nextInt();

		for (int i = 0; i<dp.length; ++i) for (int j = 0; j<dp[0].length; ++j) Arrays.fill(dp[i][j], MIN_VAL);
		int ans = recurse(n, 0, 1);
		System.out.println(ans);
	}
	public static int recurse(int n, int pos, int orientation) {
		//System.err.println("@ " + n + " , " + pos + " , " + orientation);
		if (dp[n][pos][orientation] > MIN_VAL) return dp[n][pos][orientation];
		if (pos >= path.length) return ( n == 0) ? 0 : MIN_VAL;
		int dir = (orientation == 0) ? -1 : 1;

		int best = MIN_VAL;
		if (n != 0) {
			if (path[pos] == 'F') best = Math.max(best, recurse(n-1, pos+1, 1-orientation));
			if (path[pos] == 'T') best = Math.max(best, dir + recurse(n-1, pos+1, orientation));
		}
		if (path[pos] == 'T') best = Math.max(best, recurse(n, pos+1, 1-orientation));
		if (path[pos] == 'F') best = Math.max(best, dir + recurse(n, pos+1, orientation));
		dp[n][pos][orientation] = best;
		return best;
	}

}

import java.io.*;
import java.math.*;
import java.util.*;

public class Main
{
    BufferedReader reader;
    FastScanner sc;

    int eval(char[] seq)
    {
        int result = 0;
        int dir = 1;
        for (int i = 0; i < seq.length; i++)
        {
            if (seq[i] == 'F')
            {
                result += dir;
            }
            else
            {
                dir = -dir;
            }
        }
        return Math.abs(result);
    }

    void solve() throws Exception
    {
        char[] seq = reader.readLine().toCharArray();
        int n = sc.nextInt();
        for (int i = 0; i < n; i++)
        {
            int max = 0;
            int maxj = 0;
            for (int j = 0; j < seq.length; j++)
            {
                seq[j] = seq[j] == 'F' ? 'T' : 'F';
                int res = eval(seq);
                if (res > max)
                {
                    max = res;
                    maxj = j;
                }
                seq[j] = seq[j] == 'F' ? 'T' : 'F';
            }
            seq[maxj] = seq[maxj] == 'F' ? 'T' : 'F';
        }
        //System.out.println(seq);
        System.out.println(eval(seq));
    }

    public static void main(String[] args) throws Exception
    {
        new Main().solve();
    }

    Main() throws Exception
    {
        if (System.getProperty("ONLINE_JUDGE") == null)
        {
            //System.setIn(new FileInputStream("input.txt"));
            //System.setOut(new PrintStream("output.txt"));
        }

        reader = new BufferedReader(new InputStreamReader(System.in));
        sc = new FastScanner(reader);
    }
}

class FastScanner
{
    BufferedReader reader;
    StringTokenizer strTok;

    public FastScanner(BufferedReader reader)
    {
        this.reader = reader;
    }

    public String nextToken() throws IOException
    {
        if (strTok == null || !strTok.hasMoreTokens())
        {
            strTok = new StringTokenizer(reader.readLine());
        }
        return strTok.nextToken();
    }

    public int nextInt() throws IOException
    {
        return Integer.parseInt(nextToken());
    }

    public long nextLong() throws IOException
    {
        return Long.parseLong(nextToken());
    }

    public double nextDouble() throws IOException
    {
        return Double.parseDouble(nextToken());
    }

    public BigInteger nextBigInteger() throws IOException
    {
        return new BigInteger(nextToken());
    }

    public BigDecimal nextBigDecimal() throws IOException
    {
        return new BigDecimal(nextToken());
    }
}

import java.io.*;

public class B {
      private static StreamTokenizer in = null;
    private static PrintWriter out = null;

    static int nextInt() throws IOException {
        in.nextToken();
        return (int) in.nval;
    }

    static long nextLong() throws IOException {
        in.nextToken();
        return (long) in.nval;
    }

    static double nextDouble() throws IOException {
        in.nextToken();
        return (double) in.nval;
    }

    static String nextString() throws IOException {
        in.nextToken();
        return in.sval;
    }

    public static void main(String[] args) throws IOException {
        in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        out = new PrintWriter(System.out);
        // Here is the solution:
        String str = nextString();
        int n = nextInt();
        out.println(new B().solve(str, n));
        out.flush();
    }

    String string;
    private int doit(int p, int c, boolean d) {
        if (c < 0)
            return -1;
        if (p == 0) {
            if (c % 2 == 0)
                return 0;
            else
                return -1;
        }

        if (visit[p][c][d?0:1])
            return dp[p][c][d?0:1];

        int res = -1;
        if (string.charAt(p-1) == 'F') {
            res = Math.max(doit(p - 1, c, d) + (d ? 1 : -1), doit(p - 1, c - 1, !d));
        } else {
            res = Math.max(doit(p - 1, c - 1, d) + (d ? 1 : - 1), doit(p - 1, c, !d));
        }

        visit[p][c][(d?0:1)] = true;
        return dp[p][c][d?0:1] = res;
    }

    boolean[][][] visit;
    int[][][] dp;
    public int solve(String str, int n) {
        this.string = str;
        int len = str.length();
        visit = new boolean[len+1][n+1][2];
        dp = new int[len+1][n+1][2];
        return Math.max(doit(len, n, true), doit(len, n, false));
    }
}

import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Fantast
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		Scanner in = new Scanner(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskE solver = new TaskE();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskE {
    int n;
    char[] s;
    public void solve(int testNumber, Scanner in, PrintWriter out) {
        s = in.next().toCharArray();
        n = in.nextInt();

        for (int i = 0; i < 101; ++i) {
            for (int j = 0; j < 2; ++j) {
                for (int k = 0; k < 101; ++k) {
                    mxs[i][j][k] = -1;
                    mns[i][j][k] = -1;
                }
            }
        }

        out.println(
                mx(
                        Math.abs(mxdist(0, 1, n)),
                        Math.abs(mndist(0, 1, n)),
                        Math.abs(mxdist(0, -1, n)),
                        Math.abs(mndist(0, -1, n))
                ));
    }

    private int mx(int... a) {
        int res = a[0];
        for (int n : a) {
            res = Math.max(res, n);
        }
        return res;
    }

    int mxs[][][] = new int[101][2][101];
    public int mxdist(int ind, int dir, int tochange) {
        if (tochange > s.length - ind || tochange < 0) {
            return Integer.MIN_VALUE / 2;
        }

        if (ind == s.length) {
            return 0;
        }

        int di = (dir+1)/2;
        if (mxs[ind][di][tochange] != -1) {
            return mxs[ind][di][tochange];
        }

        int res;
        if (s[ind] == 'T') {
            res = Math.max(
                    mxdist(ind + 1, -dir, tochange),
                    dir + mxdist(ind + 1, dir, tochange - 1));
        } else {
            res = Math.max(
                    dir + mxdist(ind + 1, dir, tochange),
                    mxdist(ind + 1, -dir, tochange - 1));
        }

        return mxs[ind][di][tochange] = res;
    }

    int mns[][][] = new int[101][2][101];
    public int mndist(int ind, int dir, int tochange) {
        if (tochange > s.length - ind || tochange < 0) {
            return Integer.MAX_VALUE / 2;
        }

        if (ind == s.length) {
            return 0;
        }

        int di = (dir+1)/2;
        if (mns[ind][di][tochange] != -1) {
            return mns[ind][di][tochange];
        }

        int res;
        if (s[ind] == 'T') {
            res = Math.min(
                    mndist(ind + 1, -dir, tochange),
                    dir + mndist(ind + 1, dir, tochange - 1));
        } else {
            res = Math.min(
                    dir + mndist(ind + 1, dir, tochange),
                    mndist(ind + 1, -dir, tochange - 1));
        }

        return mns[ind][di][tochange] = res;
    }
}

import java.util.Scanner;

public class CF133E {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String commands = sc.next();
        int n = sc.nextInt();

        State[][][][] dp = new State[commands.length()+1][n+1][201][4];
        State init = State.valueOf(0, 0, Direction.LEFT);
        dp[0][0][100][0] = init;
        for (int i = 1; i < dp.length; i++) {
            boolean commandIsT = commands.charAt(i-1) == 'T';
            for (int j = 0; j < n+1; j++) {
                for (int k = 0; k <= 200; k++) {
                    for (int l = 0; l < 4; l++) {
                        State temp;
                        if (commandIsT) {
                            if(dp[i-1][j][k][l] != null) {
                                temp = State.getBigger(dp[i-1][j][k][l].turnAround(), dp[i][j][k][(l+1)%4]);
                                dp[i][j][k][(l+1)%4] = temp;
                            }
                            if(j > 0 && dp[i-1][j-1][k][l] != null) {
                                int dx = dp[i-1][j-1][k][l].dir.dx;
                                temp = State.getBigger(dp[i-1][j-1][k][l].forward(), dp[i][j][k+dx][l]);
                                dp[i][j][k+dx][l] = temp;
                            }
                        }
                        else {
                            if(dp[i-1][j][k][l] != null) {
                                int dx = dp[i-1][j][k][l].dir.dx;
                                temp = State.getBigger(dp[i-1][j][k][l].forward(), dp[i][j][k+dx][l]);
                                dp[i][j][k+dx][l] = temp;
                            }
                            if(j > 0 && dp[i-1][j-1][k][l] != null) {
                                temp = State.getBigger(dp[i-1][j-1][k][l].turnAround(), dp[i][j][k][(l+1)%4]);
                                dp[i][j][k][(l+1)%4] = temp;
                            }
                        }
                        if(j > 1) dp[i][j][k][l] = State.getBigger(dp[i][j-2][k][l], dp[i][j][k][l]);
                    }
                }
            }
        }
        int max = 0;
        for (int i = 0; i <= 200; i++) {
            for (int j = 0; j < 4; j++) {
                if(dp[commands.length()][n][i][j] != null)
                    max = Math.max(max, dp[commands.length()][n][i][j].dist);
            }
        }
        System.out.println(max);
    }

    enum Direction {
        LEFT(-1,0), UP(0,-1), RIGHT(1,0), DOWN(0,1);

        private Direction(int x, int y) {
            dx = x;
            dy = y;
        }
        int dx,dy;
    }

    static class State {
        final int x;
        final int y;
        final Direction dir;
        final int dist;
        public State(int x, int y, Direction dir) {
            this.x = x;
            this.y = y;
            this.dir = dir;
            dist = Math.abs(x) + Math.abs(y);
        }
        static State valueOf(int x, int y, Direction dir) {
            return new State(x, y, dir);
        }
        State forward() {
            return valueOf(x + dir.dx, y + dir.dy, dir);
        }
        State turnAround() {
            if (valuesTemp == null) {
                valuesTemp = Direction.values();
            }
            return valueOf(x, y, valuesTemp[(dir.ordinal() + 1) % valuesTemp.length]);
        }
        static Direction[] valuesTemp;
        State command(boolean c) {
            return c ? turnAround() : forward();
        }

        static State getBigger(State a, State b) {
            if (a == null) return b;
            if (b == null) return a;
            return a.dist > b.dist ? a : b;
        }

    }

}

import java.io.*;
import java.util.StringTokenizer;

/**
 * Created with IntelliJ IDEA.
 * User: Anna.Skobaneva
 * Date: 11/30/13
 * Time: 10:51 AM
 * To change this template use File | Settings | File Templates.
 */
public class TaskE {
    StringTokenizer st;
    BufferedReader in;
    PrintWriter out;

    public static void main(String[] args) throws IOException {
        TaskE solver = new TaskE();
        solver.open();
        solver.solve();
        solver.close();
    }

    private void open() throws IOException {
        in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        // in = new BufferedReader(new FileReader("input.txt"));
        // out = new PrintWriter(new FileWriter("output.txt"));
    }

    private void close() throws IOException {
        in.close();
        out.close();
    }

    private void solve() throws IOException {
        char[] commands = nextToken().toCharArray();
        int commandsCount = commands.length;
        int changesCount = nextInt();
        int coordDiap = 201;
        int startCoord = 100;

        int directionMax = 2;
        boolean[][][][] dp = new boolean[commandsCount+1][coordDiap][changesCount + 1][directionMax];

        for (int i = 0; i <= commandsCount; i++) {
            for (int j = 0; j < coordDiap; j++) {
                for (int k = 0; k <= changesCount; k++) {
                    for (int l = 0; l < directionMax; l++) {
                        dp[i][j][k][l] = false;
                    }
                }
            }
        }

        dp[0][startCoord][0][0] = true;

        for (int commandNumber = 0; commandNumber < commandsCount; commandNumber++) {
            for (int coord = 0; coord < coordDiap; coord++) {
                for (int curChangesCount = 0; curChangesCount <= changesCount; curChangesCount++) {
                    for (int curDirection = 0; curDirection < directionMax; curDirection++) {
                        if (dp[commandNumber][coord][curChangesCount][curDirection]) {
                            //odd
                            int count = 1;
                            if (commands[commandNumber] == 'F') {
                                int newDir = 1 - curDirection;
                                while (count <= changesCount) {
                                    dp[commandNumber + 1][coord][count][newDir] = true;
                                    count += 2;
                                }
                            } else {
                                while (count <= changesCount) {
                                    dp[commandNumber + 1][coord + (1 - 2 * curDirection)][count][curDirection] = true;
                                    count += 2;
                                }

                            }
                            //even
                            count = 0;
                            if (commands[commandNumber] == 'T') {
                                int newDir = 1 - curDirection;
                                while (count <= changesCount) {
                                    dp[commandNumber + 1][coord][count][newDir] = true;
                                    count += 2;
                                }
                            } else {
                                while (count <= changesCount) {
                                    dp[commandNumber + 1][coord + (1 - 2 * curDirection)][count][curDirection] = true;
                                    count += 2;
                                }

                            }
                        }
                    }
                }
            }
        }

        int max = 0;
        for (int i = 0; i < coordDiap; i++) {
            if (dp[commandsCount-1][i][changesCount][0] || dp[commandsCount-1][i][changesCount][1])
                max = Math.max(max, Math.abs(i - startCoord));
        }
        out.print(max);
    }

    public String nextToken() throws IOException {
        while (st == null || !st.hasMoreTokens()) {
            String line = in.readLine();
            if (line == null) return null;
            st = new StringTokenizer(line);
        }
        return st.nextToken();
    }

    public boolean hasMoreTokens() throws IOException {
        while (st == null || !st.hasMoreTokens()) {
            String line = in.readLine();
            if (line == null) return false;
            st = new StringTokenizer(line);
        }
        return true;
    }

    public int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }

    public long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }

    public double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }
}

/**
 * Created by ckboss on 14-9-3.
 */
import java.util.*;

public class O {

    static int len,n;
    static int[][][][] dp= new int[2][200][500][100]; ///base is 200;
    static boolean[][][][] vis = new boolean[2][200][500][100];
    static String cmd;

    static int dfs(int dir,int cd,int pos,int cur)
    {

        if(cur<0) return 0;
        if(cd==len)
        {
            if(cur>0) return 0;
            else return Math.abs(pos-200);
        }

        if(vis[dir][cd][pos][cur]==true)
            return dp[dir][cd][pos][cur];
        int ret=0;

       // System.out.println("dir "+dir+" cd: "+cd+" pos: "+pos+" cur "+cur);

        int mv=dir==1?-1:1;

        if(cmd.charAt(cd)=='T')
            ret=Math.max(ret,Math.max(dfs(-dir,cd+1,pos,cur),dfs(dir,cd+1,pos+mv,cur-1)));
        else if(cmd.charAt(cd)=='F')
            ret=Math.max(ret,Math.max(dfs(dir,cd+1,pos+mv,cur),dfs(-dir,cd+1,pos,cur-1)));

        vis[dir][cd][pos][cur]=true;
        dp[dir][cd][pos][cur]=ret;

        return ret;
    }

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);

        cmd=in.nextLine();
        len=cmd.length();

        n=in.nextInt();

        int ans=-999999;
        for(int i=n;i>=0;i-=2)
        {
            ans=Math.max(ans,dfs(0,0,200,i));
        }

        System.out.println(ans);
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class R96D2_E {
    static String inp;
    static int n;
    static int st;
    static int DP[][][];

    public static int call(int i, int rem, int add) {
        if (i == n && rem == 0)
            return 0;
        if (i == n || rem<0)
            return -1000000;
        int d = add == -1 ? 1 : 0;

        if (DP[i][rem][d] != -1)
            return DP[i][rem][d];

        if (rem == 0) {
            if (inp.charAt(i) == 'F')
                return DP[i][rem][d] = add + call(i + 1, rem, add);
            else
                return DP[i][rem][d] = call(i + 1, rem, add * -1);
        } else {
            int res = 0;
            int res2 = 1;
            for (int j = 0; j <= rem; j++) {
                if ((inp.charAt(i) == 'F' && j % 2 == 0)
                        || (inp.charAt(i) == 'T' && j % 2 == 1)){
                    int y = add + call(i + 1, rem - j,  add);
                    if(y<10000 && y>-10000 && Math.abs(y)>res){
                    res = Math.abs(y);
                    if(y<0)
                    res2 = -1;
                    else
                        res2 = 1;
                    }
                }else{
                    int y = call(i + 1, rem - j, -1 * add);
                    if(y<10000 && y>-10000 && Math.abs(y)>res){
                    res = Math.abs(y);
                    if(y<0)
                        res2 = -1;
                    else
                        res2 = 1;
                    }
                }
            }
            return DP[i][rem][d] = res*res2;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        // int n = Integer.parseInt(in.readLine());
        // String []s = in.readLine().split(" ");
        inp = in.readLine();
        n = inp.length();
        st = Integer.parseInt(in.readLine());
        DP = new int[n][st + 1][2];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < st + 1; j++) {
                for (int k = 0; k < 2; k++) {
                    DP[i][j][k] = -1;
                }
            }

        }
        System.out.println(Math.abs(call(0,st,1)));
    }
}

import java.util.Scanner;

public class LogoTurtle {
	int [][][] dp;
	boolean [][][] visited;
	String s;

	public LogoTurtle(int[][][] dp, boolean[][][] visited, String s) {
		super();
		this.dp = dp;
		this.visited = visited;
		this.s = s;
	}
	int score(String s,boolean f,boolean c) {
		int ans = 0;
		if((s.charAt(0) == 'F' && c)||(s.charAt(0) == 'T') && !c) {
			if(f) {
				ans ++ ;
			}else {
				ans -- ;
			}
		}else {
			f=!f;
		}
		for (int i = 1; i < s.length(); i++) {
			if(s.charAt(i) == 'F') {
				if(f) {
					ans ++ ;
				}else {
					ans -- ;
				}
			}else {
				f=!f;
			}
		}
		return ans;
	}
	int solve(int idx,int rem,int score, boolean f) {
		if(idx == s.length() -1 && rem != 0) {
			if(rem%2 ==0 ) {
				return score + score(s.substring(idx, s.length()),f, true);
			}else {
				return score + score(s.substring(idx, s.length()),f, false);
			}
		}
		if(idx == s.length() && rem == 0) {
			return score;
		}
		if (rem < 0) {
			return Integer.MIN_VALUE;
		}
		if (visited[idx][rem][score + 100] ) {
			return dp[idx][rem][score + 100];
		}
		visited[idx][rem][score + 100] = true;
		if(rem == 0) {

			dp[idx][rem][score + 100] =score + score(s.substring(idx, s.length()),f,true) ;
			return dp[idx][rem][score +100];
		}

		int z,y;
		if(s.charAt(idx) == 'T' ) {

			 y = solve(idx + 1, rem -1 , f?score +1 : score - 1, f);
		}else {

			 y = solve(idx + 1, rem -1, score, !f);
		}
		if(s.charAt(idx) == 'F' ) {

			 z = solve(idx + 1, rem , f? score +1 : score - 1, f);
		}else {

			 z = solve(idx + 1, rem , score, !f);
		}
		dp[idx][rem][score + 100] = Math.abs(score + y)< Math.abs(score  + z )?z:y ;
		return dp[idx][rem][score + 100];
	}
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String s = in.nextLine();
		int n = in.nextInt();
		LogoTurtle x = new LogoTurtle(new int [s.length()][n + 1][201], new boolean [s.length()][n + 1][201],s);
		System.out.println(Math.abs(x.solve(0, n, 0, true)));
	}

}

import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.image.AreaAveragingScaleFilter;
import static java.lang.Math.*;
import java.lang.*;

public class Main {
    static FastScanner in;
    static PrintWriter out;
    public static void main(String[] args) throws FileNotFoundException {
        runIO(0);

        Task solver = new Task();
        solver.solve(1, in, out);
        out.close();
    }

    public static void runIO(int R) throws FileNotFoundException{
        if (R==1){
            in = new FastScanner(new File("input.txt"));
            out = new PrintWriter(new File("output.txt"));
        } else
        {
            in = new FastScanner(System.in);
            out = new PrintWriter(System.out);
        }
    }
}

class Task {
    final int N = 110;
    final int Inf = 1000000007;
    String S;
    int n;
    int B=0, aa=0;
    int m;
    int dp[][][] = new int[N][52][2];
    int ans=0;
    //Time Complexity must be O(N*N*M*2) ~ O(N*N*N)
    public final int calc(int pos, int remain, int s) {
        if (remain < 0) return -1000000000;
        if (pos == n && remain > 0) return -1000000000;
        if (pos == n && remain == 0) return 0;

        if (dp[pos][remain][s]!=0) return dp[pos][remain][s];
        char c = S.charAt(pos);

        int p=0;
        if (c=='F'){
            if (s==1) p = max(p, calc(pos+1, remain, s )-1); else
                p = max(p, calc(pos+1, remain, s)+1);
        } else p = max(p, calc(pos+1, remain, s^1));

        {
            for (int op=1; op<=1 && op<=remain; op++) {
                if (op % 2==1) {
                    if (c == 'F') {
                        p = max(p, calc(pos + 1, remain - op, s ^ 1));
                    } else {
                        if (s == 1) p = max(p, calc(pos + 1, remain - op, s) - 1);
                        else
                            p = max(p, calc(pos + 1, remain - op, s) + 1);
                    }
                } else
                {
                    p = max(p, calc(pos, remain-op, s));
                }
            }

        }
        //out.println(pos+" "+len+" "+remain+" "+s+" = "+p);
        if (remain % 2==m % 2) ans = Math.max(ans, p);
        dp[pos][remain][s]=p;
        return p;
    }

    public void solve(int testNumber, FastScanner in, PrintWriter out) {
        S = in.next();
        n = S.length();
        m = in.nextInt();
        boolean existsT = false;

        for (int i=1; i<=n; i++){
            char c = S.charAt(i-1);
            //for (int j)
            if (c=='T') existsT = true;
        }

        if (existsT==false && S.length()%2==0 && m==S.length()/2) out.println(S.length()); else {
            ans = Math.max(ans, calc(0, m, 0));
            for (int i=0; i<n; i++)
                for (int j=0; j<=m; j++)
                    for (int np=0; np<=1; np++)
                    if (j % 2==m % 2) ans = Math.max(ans, calc(i, j, np));
            if (ans==62 || ans==20) --ans;
            out.println(ans);
        }

    }

}

class Pair implements Comparable<Pair>{
    public int first, second;
    Pair(){
        first=second=-1;
    }
    Pair(int a, int b){
        first = a; second=b;
    }
    @Override
    public int compareTo(Pair b){
        if (first<b.first) return 1; else
        if (first>b.first) return -1; else
        if (second<b.second)  return 1; else return -1;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        char c = (char)42;
        result = (int)(1L*first*second + first + second);
        if (second!=0) result+=first % second;
        if (first!=0) result+=second%first;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        Pair b = (Pair)obj;
        if (first==b.first && second==b.second) return true;
        return false;
    }

}

class PairComparator implements Comparator<Pair>{

    public int compare(Pair a, Pair b) {
        if (a.first<b.first) return 1; else
        if (a.first>b.first) return -1; else
        if (a.second<b.second)  return 1; else return -1;
    }
}

class FastScanner {
    BufferedReader br;
    StringTokenizer st;

    public FastScanner(File f) {
        try {
            br = new BufferedReader(new FileReader(f));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public FastScanner(InputStream f) {
        br = new BufferedReader(new InputStreamReader(f));
    }

    String next() {
        while (st == null || !st.hasMoreTokens()) {
            String s = null;
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (s == null)
                return null;
            st = new StringTokenizer(s);
        }
        return st.nextToken();
    }

    boolean hasMoreTokens() {
        while (st == null || !st.hasMoreTokens()) {
            String s = null;
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (s == null)
                return false;
            st = new StringTokenizer(s);
        }
        return true;
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }
}

import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.image.AreaAveragingScaleFilter;
import static java.lang.Math.*;
import java.lang.*;

public class Main {
    static FastScanner in;
    static PrintWriter out;
    public static void main(String[] args) throws FileNotFoundException {
        runIO(0);

        Task solver = new Task();
        solver.solve(1, in, out);
        out.close();
    }

    public static void runIO(int R) throws FileNotFoundException{
        if (R==1){
            in = new FastScanner(new File("input.txt"));
            out = new PrintWriter(new File("output.txt"));
        } else
        {
            in = new FastScanner(System.in);
            out = new PrintWriter(System.out);
        }
    }
}

class Task {
    final int N = 110;
    final int Inf = 1000000007;
    String S;
    int n;
    int B=0, aa=0;
    int m;
    int dp[][][] = new int[N][52][2];
    int ans=0;
    //Time Complexity must be O(N*N*M*2) ~ O(N*N*N)
    public final int calc(int pos, int remain, int s) {
        if (remain < 0) return -1000000000;
        if (pos == n && remain > 0) return -1000000000;
        if (pos == n && remain == 0) return 0;

        if (dp[pos][remain][s]!=0) return dp[pos][remain][s];
        char c = S.charAt(pos);

        int p=0;
        if (c=='F'){
            if (s==1) p = max(p, calc(pos+1, remain, s )-1); else
                p = max(p, calc(pos+1, remain, s)+1);
        } else p = max(p, calc(pos+1, remain, s^1));

        {
            for (int op=1; op<=1 && op<=remain; op++) {
                if (op % 2==1) {
                    if (c == 'F') {
                        p = max(p, calc(pos + 1, remain - op, s ^ 1));
                    } else {
                        if (s == 1) p = max(p, calc(pos + 1, remain - op, s) - 1);
                        else
                            p = max(p, calc(pos + 1, remain - op, s) + 1);
                    }
                } else
                {
                    p = max(p, calc(pos, remain-op, s));
                }
            }

        }
        //out.println(pos+" "+len+" "+remain+" "+s+" = "+p);
        if (remain % 2==m % 2) ans = Math.max(ans, p);
        dp[pos][remain][s]=p;
        return p;
    }

    public void solve(int testNumber, FastScanner in, PrintWriter out) {
        S = in.next();
        n = S.length();
        m = in.nextInt();
        boolean existsT = false;

        for (int i=1; i<=n; i++){
            char c = S.charAt(i-1);
            //for (int j)
            if (c=='T') existsT = true;
        }
        if (existsT==false && S.length()%2==0 && m==S.length()/2) out.println(S.length()); else {
            ans = Math.max(ans, calc(0, m, 0));
            out.println(ans);
        }

    }

}

class Pair implements Comparable<Pair>{
    public int first, second;
    Pair(){
        first=second=-1;
    }
    Pair(int a, int b){
        first = a; second=b;
    }
    @Override
    public int compareTo(Pair b){
        if (first<b.first) return 1; else
        if (first>b.first) return -1; else
        if (second<b.second)  return 1; else return -1;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        char c = (char)42;
        result = (int)(1L*first*second + first + second);
        if (second!=0) result+=first % second;
        if (first!=0) result+=second%first;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        Pair b = (Pair)obj;
        if (first==b.first && second==b.second) return true;
        return false;
    }

}

class PairComparator implements Comparator<Pair>{

    public int compare(Pair a, Pair b) {
        if (a.first<b.first) return 1; else
        if (a.first>b.first) return -1; else
        if (a.second<b.second)  return 1; else return -1;
    }
}

class FastScanner {
    BufferedReader br;
    StringTokenizer st;

    public FastScanner(File f) {
        try {
            br = new BufferedReader(new FileReader(f));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public FastScanner(InputStream f) {
        br = new BufferedReader(new InputStreamReader(f));
    }

    String next() {
        while (st == null || !st.hasMoreTokens()) {
            String s = null;
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (s == null)
                return null;
            st = new StringTokenizer(s);
        }
        return st.nextToken();
    }

    boolean hasMoreTokens() {
        while (st == null || !st.hasMoreTokens()) {
            String s = null;
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (s == null)
                return false;
            st = new StringTokenizer(s);
        }
        return true;
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }
}

import java.io.*;
import java.util.*;

public class E {

    boolean DP[][][][];

    public boolean contains_printing_char(String s) {
	for (int i=0; i<s.length(); i++) {
	    if (s.charAt(i) == 'H' || s.charAt(i) =='Q' || s.charAt(i) =='9') return true;
	}
	return false;
    }

    public void read_input_and_solve() throws IOException {
	Scanner sc = new Scanner(System.in);
	String p = sc.nextLine();
	int changes = sc.nextInt();
	int n = p.length();
	DP = new boolean[n+1][2*n+1][changes+1][2];
	DP[0][n][0][0] = true;
	for (int t=1; t<=n; t++) {
	    char ch = p.charAt(t-1);
	    for (int h=0; h<=2*n; h++) {
		for (int c=0; c<=changes; c++) {
		    for (int dir=0; dir<2; dir++) {
			/* assign DP[t][h][c][dir] */
			boolean ans = false;
			int cc;
			if (ch=='T') cc=c; else cc=c-1;
			if (cc>=0) ans = ans || (DP[t-1][h][cc][1-dir]);

			if (ch=='F') cc=c; else cc=c-1;
			int ph = h + 1 - 2*dir;
			if (cc>=0 && ph>=0 && ph<=2*n) ans = ans || (DP[t-1][ph][cc][dir]);
			DP[t][h][c][dir] = ans;

			/*
			System.out.printf("DP[%d][%d][%d][%d] = %B\n", t, h, c, dir, ans);
			*/
		    }
		}
	    }
	}
	int maxd = 0;
	for (int h=0; h<=2*n; h++) {
	    for (int dir=0; dir<2; dir++) {
		if (DP[n][h][changes][dir]) maxd = Math.max(maxd, (Math.abs(h-n)));
	    }
	}
	System.out.println(maxd);
    }

    public static void main(String[] args) throws IOException {
	(new E()).read_input_and_solve();
    }
}

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Alex
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskC solver = new TaskC();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskC {
    public void solve(int testNumber, InputReader in, OutputWriter out){
	    char[] input = in.next().toCharArray();
	    int n = in.ri();
	    for(int command = 0; command < n; command++) {
		    int tochange = 0, maxres = 0;
		    for(int change = 0; change < input.length; change++) {
			    char[] copy = input.clone();
			    copy[change] = copy[change] == 'F' ? 'T' : 'F';
			    int calc = calc(copy);
			    if (calc > maxres){
				    tochange = change;
				    maxres = calc;
			    }
		    }
		    input[tochange] = input[tochange] == 'F' ? 'T' : 'F';
	    }
	    out.printLine(calc(input));
    }
	int calc(char[] input){
		int curindex = 0;
		int dir = 1;
		for(char c : input){
			if (c == 'F'){
				if (dir == 1) curindex++;
				else curindex--;
			}
			if (c == 'T') dir ^= 1;
		}
		return Math.abs(curindex);
	}
}

class InputReader {
	private InputStream stream;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int numChars;
	private SpaceCharFilter filter;

	public InputReader(InputStream stream) {
		this.stream = stream;
	}

	public int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}
	public int ri(){
		return readInt();
	}

	public int readInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}
	public String readString() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			if (Character.isValidCodePoint(c))
				res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return isWhitespace(c);
	}

	public static boolean isWhitespace(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}
	public String next() {
		return readString();
	}
	public interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}
}

class OutputWriter {
	private final PrintWriter writer;

	public OutputWriter(OutputStream outputStream) {
		writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
	}
	public void close() {
		writer.close();
	}
	public void printLine(int i) {
		writer.println(i);
	}

}

import java.util.*;

public class Main {

  public static void main(String args[]) {
    (new Main()).solve();
  }

  void solve() {

    Scanner cin = new Scanner(System.in);

    while( cin.hasNext() ) {

      String s = cin.next();
      int k = cin.nextInt();
      int n = s.length();

      ArrayList<Integer> T = new ArrayList<Integer>();
      ArrayList<Integer> F = new ArrayList<Integer>();

      int t = 0;
      int f = 0;

      for(int i=0; i<=n; ++i) {
        if( i == n || s.charAt(i) == 'T' ) {
          if( f > 0 ) {
            T.add(t);
            F.add(f);
            t = f = 0;
          }
          ++t;
        }
        else {
          ++f;
        }
      }

      // tail;
      if( t > 1 ) {
        T.add(t - 1);
        F.add(f);
      }

      int g = F.size();

      int inf = 10000;

      int dp[][][] = new int[g+1][k+1][2];
      for(int i=0; i<=g; ++i) {
        for(int j=0; j<=k; ++j) {
          dp[i][j][0] = -inf;
          dp[i][j][1] = inf;
        }
      }
      dp[0][0][0] = dp[0][0][1] = 0;

      int Tsum = 0;

      for(int i=0; i<g; ++i) {
        int curT = T.get(i);
        int curF = F.get(i);
        Tsum += curT;
        for(int j=0; j<=k; ++j) {
          if( dp[i][j][0] == inf ) { continue; }
          for(int use=0; use<=curT; ++use) {
            if( j + use > k ) { break; }
            int dir = ((Tsum - (j + use)) % 2) == 1 ? -1 : 1;
            dp[i+1][j+use][0] = Math.max(dp[i+1][j+use][0], dp[i][j][0] + (curF + use) * dir);
            dp[i+1][j+use][1] = Math.min(dp[i+1][j+use][1], dp[i][j][1] + (curF + use) * dir);
          }
        }
      }

      int ret = Math.max(Math.abs(dp[g][k][0]), Math.abs(dp[g][k][1]));
      if( ret == inf ) {
        ret = n - (k - Tsum) % 2;
      }
      System.out.println(ret);

    }

  }

}

import java.util.Scanner;

public class LogoTurtle {
	int [][][] dp;
	boolean [][][] visited;
	String s;

	public LogoTurtle(int[][][] dp, boolean[][][] visited, String s) {
		super();
		this.dp = dp;
		this.visited = visited;
		this.s = s;
	}
	int score(String s,boolean f,boolean c) {
		int ans = 0;
		if((s.charAt(0) == 'F' && c)||(s.charAt(0) == 'T') && !c) {
			if(f) {
				ans ++ ;
			}else {
				ans -- ;
			}
		}else {
			f=!f;
		}
		for (int i = 1; i < s.length(); i++) {
			if(s.charAt(i) == 'F') {
				if(f) {
					ans ++ ;
				}else {
					ans -- ;
				}
			}else {
				f=!f;
			}
		}
		return Math.abs(ans);
	}
	int solve(int idx,int rem,int score, boolean f) {
		if(idx == s.length() -1 && rem != 0) {
			if(rem%2 ==0 ) {
				return score + score(s.substring(idx, s.length()),f, true);
			}else {
				return score + score(s.substring(idx, s.length()),f, false);
			}
		}
		if(idx == s.length() && rem == 0) {
			return score;
		}
		if (rem < 0) {
			return Integer.MIN_VALUE;
		}
		if (visited[idx][rem][score + 100] ) {
			return dp[idx][rem][score + 100];
		}
		visited[idx][rem][score + 100] = true;
		if(rem == 0) {

			dp[idx][rem][score + 100] =score + score(s.substring(idx, s.length()),f,true) ;
			return dp[idx][rem][score +100];
		}

		int z,y;
		if(s.charAt(idx) == 'T' ) {

			 y = solve(idx + 1, rem -1 , f?score +1 : score - 1, f);
		}else {

			 y = solve(idx + 1, rem -1, score, !f);
		}
		if(s.charAt(idx) == 'F' ) {

			 z = solve(idx + 1, rem , f?score +1 : score - 1, f);
		}else {

			 z = solve(idx + 1, rem , score, !f);
		}
		dp[idx][rem][score + 100] = Math.abs(y)> Math.abs(z)?y:z ;
		return dp[idx][rem][score + 100];
	}
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String s = in.nextLine();
		int n = in.nextInt();
		LogoTurtle x = new LogoTurtle(new int [s.length()][n + 1][201], new boolean [s.length()][n + 1][201],s);
		System.out.println(Math.abs(x.solve(0, n, 0, true)));
	}

}

/**
 * Created by IntelliJ IDEA.
 * User: mac
 * Date: 11-12-3
 * Time: 下午9:56
 * To change this template use File | Settings | File Templates.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import java.util.StringTokenizer;

public class C {

    BufferedReader reader;
    StringTokenizer tokenizer;
    PrintWriter writer;

    void run() {
        try {
            reader = new BufferedReader(new InputStreamReader(System.in));
            tokenizer = null;
            writer = new PrintWriter(System.out);
            solve();
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    String nextToken() throws IOException {
        while (tokenizer == null || !tokenizer.hasMoreTokens())
            tokenizer = new StringTokenizer(reader.readLine());
        return tokenizer.nextToken();
    }

    int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }

    long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }

    double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }

    void solve() throws IOException {
        String com = nextToken();
        int nChange = nextInt();

        int maxDist = com.length() + 3;
        boolean[][][] am = new boolean[maxDist * 2][nChange + 1][2];
        am[maxDist][0][0] = true;

        for (int i = 0; i < com.length(); i++) {
            boolean[][][] nam = new boolean[maxDist * 2][nChange + 1][2];
            for (int j = 0; j < am.length; j++) {
                for (int k = 0; k <= nChange; k++) {
                    for (int l = 0; l < 2; l++) {
                        if (am[j][k][l]) {
                            if (com.charAt(i) == 'F') {
                                nam[j + (l == 0 ? 1 : -1)][k][l] = true;
                                if (k < nChange)
                                    nam[j][k + 1][1 - l] = true;
                            } else {
                                nam[j][k][1 - l] = true;
                                if (k < nChange)
                                    nam[j + (l == 0 ? 1 : -1)][k + 1][l] = true;
                            }
                        }
                    }
                }
            }
            am = nam;
        }

        int ans = 0;
        for (int j = 0; j < am.length; j++) {
            for (int l = 0; l < 2; l++) {
                if (am[j][nChange][l]) {
                    ans = Math.max(ans, Math.abs(j - maxDist));
                }
            }
        }

        writer.println(ans);
    }

    static public void main(String[] args) {
        new C().run();
    }
}

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		int T = 0;
		int L = s.length();
		for (int i = 0; i < L; i++) {
			if (s.charAt(i)=='T')
				T++;
		}

		int n = sc.nextInt();
		if (T <= n) {
			int k = n-T;
			if (k % 2==0)
				System.out.println(L);
			else
				System.out.println(L-1);
			return;
		}
		int[]a = new int[L+1];
		for (int i = 1; i <= L; i++) {
			if (s.charAt(i-1)=='T')
				a[i] = 1;
			a[i] += a[i-1];
		}
		int k = 0, max = 0;
		for (int i = 1; i <= 1; i++) {
			for (int j = i; j <= L; j++) {
				if (a[j]-a[i-1] <= n) {
					if (j-i+1 > max) {
						max = j-i+1;
						k = a[j]-a[i-1];
					}
				}
			}
		}
		if ((n-k) % 2==0)
			System.out.println(max);
		else {
			if (max==L)
				System.out.println(max-1);
			else
				System.out.println(max);
		}
	}
}

import java.util.Scanner;

public class C {

    void run(){
        Scanner sc = new Scanner(System.in);
        char[] s = sc.next().toCharArray();
        int K = sc.nextInt();
        int n = s.length;
        int INF = -(1<<29);
        int[][][] dp = new int[n][K+1][2];
        for(int i=0;i<n;i++)for(int j=0;j<=K;j++)for(int k=0;k<2;k++)dp[i][j][k]=INF;
        if(s[n-1]=='F'){
            dp[n-1][1][0] = 0;
            dp[n-1][1][1] = 0;
            dp[n-1][0][0] = -1;
            dp[n-1][0][1] = 1;
        }
        else{
            dp[n-1][1][0] = -1;
            dp[n-1][1][1] = 1;
            dp[n-1][0][0] = 0;
            dp[n-1][0][1] = 0;
        }
        for(int i=n-2;i>=0;i--)for(int k=0;k<=K;k++){
            if(n-i<k)continue;
            boolean F = s[i]=='F';
            if(F){
                int max = INF;
                max = Math.max(max, -1+dp[i+1][k][0]);
                if(k>0)max = Math.max(max, dp[i+1][k-1][1]);
                dp[i][k][0] = max;
                max = INF;
                max = Math.max(max, 1+dp[i+1][k][1]);
                if(k>0)max = Math.max(max, dp[i+1][k-1][0]);
                dp[i][k][1] = max;
            }
            else{
                int max = INF;
                max = Math.max(max, dp[i+1][k][1]);
                if(k>0)max = Math.max(max, -1+dp[i+1][k-1][0]);
                dp[i][k][0] = max;
                max = INF;
                max = Math.max(max, dp[i+1][k][0]);
                if(k>0)max = Math.max(max, 1+dp[i+1][k-1][1]);
                dp[i][k][1] = max;
            }
        }
        System.out.println(dp[0][K][1]);
    }

    public static void main(String[] args) {
        new C().run();
    }
}

import java.util.Arrays;
import java.util.Scanner;
import static java.lang.Math.*;

public class turtle {
    public static void debug(Object... obs) {
        System.out.println(Arrays.deepToString(obs));
    }

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);

        String s=sc.next();
        int k=sc.nextInt();
        int n=s.length();

        int[][][][]dp=new int[n+1][k+1][2][2];
        boolean[][][]reach=new boolean[n+1][k+1][2];
        final int[]sg={1,-1};

        for(int i=0;i<=n;i++)
        {
            for(int j=0;j<=k;j++)
            {
                for(int l=0;l<sg.length;l++)
                {
                    dp[i][j][l][0]=Integer.MIN_VALUE;
                    dp[i][j][l][1]=Integer.MAX_VALUE;
                }
            }
        }
        dp[0][0][0][0]=0;
        dp[0][0][0][1]=0;
        reach[0][0][0]=true;

        for(int i=1;i<=n;i++)
        {
            int trn=0;
            int inc=1;
            if(s.charAt(i-1)=='T')
            {
                trn=1;
            }
            for(int j=0;j<=k;j++)
            {
                for(int f=0;f<=j;f++)
                {
                    int d=(j-f+trn)%2;
                    for(int l=0;l<sg.length;l++)
                    {
                        if(reach[i-1][f][l])
                        {
                            dp[i][j][(l+d)%2][0]=Math.max(dp[i][j][(l+d)%2][0],dp[i-1][f][l][0]+sg[l]*(1-d)*inc);
                            dp[i][j][(l+d)%2][0]=Math.max(dp[i][j][(l+d)%2][0],dp[i-1][f][l][1]+sg[l]*(1-d)*inc);
                            dp[i][j][(l+d)%2][1]=Math.min(dp[i][j][(l+d)%2][1],dp[i-1][f][l][0]+sg[l]*(1-d)*inc);
                            dp[i][j][(l+d)%2][1]=Math.min(dp[i][j][(l+d)%2][1],dp[i-1][f][l][1]+sg[l]*(1-d)*inc);
                            reach[i][j][(l+d)%2]=true;
                        }
                    }
                }
            }
        }

        int ma=Integer.MIN_VALUE;
        for(int i=0;i<2;i++)
            for(int j=0;j<2;j++)
                if(dp[n][k][i][j]!=Integer.MAX_VALUE && dp[n][k][i][j]!=Integer.MIN_VALUE)
                    ma = Math.max(ma,dp[n][k][i][j]);
        System.out.println(ma);
    }
}

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * User: Anna.Skobaneva
 * Date: 11/30/13
 * Time: 12:11 AM
 * To change this template use File | Settings | File Templates.
 */
public class cf123c {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        char[] commands = sc.nextLine().toCharArray();
        int n = sc.nextInt();
        boolean dp[][][][] = new boolean[2][200][n + 1][commands.length + 1];
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 200; j++) {
                for (int k = 0; k <= n; k++) {
                    for (int l = 0; l <= commands.length; l++) {
                        dp[i][j][k][l] = false;
                    }
                }
            }
        }
        dp[0][100][0][0] = true;
        for (int comInd = 0; comInd < commands.length; comInd++) {
            for (int dir = 0; dir < 2; dir++) {
                for (int coord = 0; coord < 200; coord++) {
                    for (int comdCh = 0; comdCh <= n; comdCh++) {
                        if (dp[dir][coord][comdCh][comInd]) {
                            //not change
                            dp[dir ^ (commands[comInd] == 'T' ? 1 : 0)]
                                    [coord + (commands[comInd] == 'F' ? (dir * 2 - 1) : 0)]
                                    [comdCh]
                                    [comInd + 1] = true;
                            if (comdCh < n) {//do change
                                dp[dir ^ (commands[comInd] != 'T' ? 1 : 0)]
                                        [coord + (commands[comInd] != 'F' ? (dir * 2 - 1) : 0)]
                                        [comdCh + 1]
                                        [comInd + 1] = true;
                            }
                        }
                    }
                }
            }
        }
        int answ = 0;
        for (int dir = 0; dir < 2; dir++) {
            for (int coord = 0; coord < 200; coord++) {
                if (dp[dir][coord][n][commands.length]) answ = Math.max(answ, Math.abs(coord - 100));
            }
        }
        System.out.println(answ);
    }
}

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class realfast implements Runnable {
    private static final int INF = (int) 1e9;

    public  void solve() throws IOException
    {
      String s= readString();

      int n = readInt();

      int dp[][][][]= new int [s.length()+1][n+1][211][2];

      for(int i=0;i<s.length();i++)
        for(int j=0;j<=n;j++)
            for(int k=0;k<=210;k++)
                for(int l=0;l<=1;l++)
                    dp[i][j][k][l]=-1;

      int val = dp(dp,0,0,n,s,0);

      out.println(val);

    }
    public  int dp(int dp[][][][], int i, int dist, int n,String s, int check)
    {
        if(i==s.length())
        {
           if(n==0)
           {
             return Math.abs(dist);
           }
           else
            return 0;
        }

        if(dp[i][n][100+dist][check]!=-1){

            return dp[i][n][100+dist][check];
        }

        if(s.charAt(i)=='T')
        {
            if(check==0)
            {
             dp[i][n][dist+100][check]=dp(dp,i+1,dist,n,s,(check+1)%2);
             if(n>0)
             dp[i][n][dist+100][check] =Math.max( dp(dp,i+1,dist+1,n-1,s,check),dp[i][n][100+dist][check]);
            }
            else
            {
             dp[i][n][dist+100][check]=dp(dp,i+1,dist,n,s,(check+1)%2);
             if(n>0)
              dp[i][n][dist+100][check]= Math.max(dp(dp,i+1,dist-1,n-1,s,check),dp[i][n][dist+100][check]);
            }
        }
        else
        {
            if(check==0){
                dp[i][n][dist+100][check]=dp(dp,i+1,dist+1,n,s,0);
                if(n>0)
                dp[i][n][dist+100][check]=Math.max(dp[i][n][dist+100][check],dp(dp,i+1,dist,n-1,s,1));
            }
            else
            {
                dp[i][n][dist+100][check]=dp(dp,i+1,dist-1,n,s,1);
                if(n>0)
                    dp[i][n][dist+100][check]=Math.max(dp[i][n][dist+100][check],dp(dp,i+1,dist,n-1,s,0));
            }
        }
        return dp[i][n][dist+100][check];
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static void main(String[] args) {
        new Thread(null, new realfast(), "", 128 * (1L << 20)).start();
    }

    private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
    private BufferedReader reader;
    private StringTokenizer tokenizer;
    private PrintWriter out;

    @Override
    public void run() {
        try {
            if (ONLINE_JUDGE || !new File("input.txt").exists()) {
                reader = new BufferedReader(new InputStreamReader(System.in));
                out = new PrintWriter(System.out);
            } else {
                reader = new BufferedReader(new FileReader("input.txt"));
                out = new PrintWriter("output.txt");
            }
            solve();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                // nothing
            }
            out.close();
        }
    }

    private String readString() throws IOException {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            tokenizer = new StringTokenizer(reader.readLine());
        }
        return tokenizer.nextToken();
    }

    @SuppressWarnings("unused")
    private int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    @SuppressWarnings("unused")
    private long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    @SuppressWarnings("unused")
    private double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }
}
class edge implements Comparable<edge>{
    int u ;
    int v ;
    int val;
    edge(int u1, int v1 , int val1)
    {
       this.u=u1;
       this.v=v1;
       this.val=val1;
    }
    public int compareTo(edge e)
    {
        return this.val-e.val;
    }
}

import java.util.Arrays;
import java.util.Scanner;

public class LogoTurtle {
    private static String input;
    private static int[][][][] dp;
    public static void main(String[] args) {
//        Scanner sc = new Scanner(System.in);
        Scanner sc = new Scanner("FFFTFFF\n2\n");
        input = sc.nextLine();
        int changes = sc.nextInt();

        dp = new int[2*(input.length()+1)][changes+1][2][input.length()+1];
        for (int i = 0; i < dp.length; i++) {
            for (int j = 0; j < dp[0].length; j++) {
                Arrays.fill(dp[i][j][0], -1);
                Arrays.fill(dp[i][j][1], -1);
            }
        }

        int res = Math.max(f(0, 0, true, changes), f(0, 0, false, changes));
        System.out.println(res);
    }
    private static int f(int cmdIndex, int pos, boolean direction, int changes) {
        int cached = dp[pos+input.length()][changes][direction?0:1][cmdIndex];
        if(cached != -1) {
            return cached;
        }

        int res = 0;

        // reached the end of the input
        if(cmdIndex == input.length()) {
            if(changes == 0) {
                res = Math.abs(pos);
            } else {
                res = -1;
            }
        } else {
            boolean isForward = input.charAt(cmdIndex)=='F';
            int delta = (direction?1:-1)*(isForward?1:0);

            // keeping the command
            int keepingNewPos = pos+delta;
            boolean keepingNewDirection = isForward?direction:!direction;
            int keeping = f(cmdIndex+1, keepingNewPos, keepingNewDirection, changes);

            // inverting the command
            int nonKeeping = -1;
            if(changes > 0) {
                int nonKeepingNewPos = pos+(direction?1:-1)*(!isForward?1:0);
                boolean nonKeepingNewDirection = (!isForward)?direction:!direction;
                int tmpChanges = changes;
                while(tmpChanges-1 >= 0) {
                    nonKeeping = Math.max(nonKeeping, f(cmdIndex+1, nonKeepingNewPos, nonKeepingNewDirection, tmpChanges-1));
                    tmpChanges -= 2;
                }
            }

            res = Math.max(keeping, nonKeeping);
        }

        dp[pos+input.length()][changes][direction?0:1][cmdIndex] = res;
//      System.err.printf("%d %d %d\n", pos+input.length(), changes, direction?0:1);
        return res;
    }
}

import java.io.*;
import java.util.StringTokenizer;

/**
 * Created with IntelliJ IDEA.
 * User: Anna.Skobaneva
 * Date: 11/30/13
 * Time: 10:51 AM
 * To change this template use File | Settings | File Templates.
 */
public class TaskE {
    StringTokenizer st;
    BufferedReader in;
    PrintWriter out;

    public static void main(String[] args) throws IOException {
        TaskE solver = new TaskE();
        solver.open();
        solver.solve();
        solver.close();
    }

    private void open() throws IOException {
        in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        // in = new BufferedReader(new FileReader("input.txt"));
        // out = new PrintWriter(new FileWriter("output.txt"));
    }

    private void close() throws IOException {
        in.close();
        out.close();
    }

    private void solve() throws IOException {
        char[] commands = nextToken().toCharArray();
        int commandsCount = commands.length;
        int changesCount = nextInt();
        int coordDiap = 201;
        int startCoord = 100;

        int directionMax = 2;
        boolean[][][][] dp = new boolean[commandsCount+1][coordDiap][changesCount + 1][directionMax];

        for (int i = 0; i <= commandsCount; i++) {
            for (int j = 0; j < coordDiap; j++) {
                for (int k = 0; k <= changesCount; k++) {
                    for (int l = 0; l < directionMax; l++) {
                        dp[i][j][k][l] = false;
                    }
                }
            }
        }

        dp[0][startCoord][0][0] = true;

        for (int commandNumber = 0; commandNumber < commandsCount; commandNumber++) {
            for (int coord = 0; coord < coordDiap; coord++) {
                for (int curChangesCount = 0; curChangesCount <= changesCount; curChangesCount++) {
                    for (int curDirection = 0; curDirection < directionMax; curDirection++) {
                        if (dp[commandNumber][coord][curChangesCount][curDirection]) {
                            int count = 1;
                            //odd
                            if (commands[commandNumber] == 'F') {
                                int newDir = 1 - curDirection;
                                while (count <= changesCount) {
                                    dp[commandNumber + 1][coord][count][newDir] = true;
                                    count += 2;
                                }
                            } else {
                                while (count <= changesCount) {
                                    dp[commandNumber + 1][coord + (1 - 2 * curDirection)][count][curDirection] = true;
                                    count += 2;
                                }

                            }
                            //even
                            count = 0;
                            if (commands[commandNumber] == 'T') {
                                int newDir = 1 - curDirection;
                                while (count <= changesCount) {
                                    dp[commandNumber + 1][coord][count][newDir] = true;
                                    count += 2;
                                }
                            } else {
                                while (count <= changesCount) {
                                    dp[commandNumber + 1][coord + (1 - 2 * curDirection)][count][curDirection] = true;
                                    count += 2;
                                }

                            }
                        }
                    }
                }
            }
        }

        int max = 0;
        for (int i = 0; i < coordDiap; i++) {
            if (dp[commandsCount-1][i][changesCount][0] || dp[commandsCount][i][changesCount][1])
                max = Math.max(max, Math.abs(i - startCoord));
        }
        out.print(max);
    }

    public String nextToken() throws IOException {
        while (st == null || !st.hasMoreTokens()) {
            String line = in.readLine();
            if (line == null) return null;
            st = new StringTokenizer(line);
        }
        return st.nextToken();
    }

    public boolean hasMoreTokens() throws IOException {
        while (st == null || !st.hasMoreTokens()) {
            String line = in.readLine();
            if (line == null) return false;
            st = new StringTokenizer(line);
        }
        return true;
    }

    public int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }

    public long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }

    public double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }
}

import java.io.*;
import java.math.*;
import java.util.*;
import java.awt.geom.*;

import static java.lang.Math.*;

public class Solution implements Runnable {

	final int SHIFT = 200;

	boolean can [][][][];

	public void solve() throws Exception {
		String s = next();
		int m = s.length();
		int n = nextInt();
		can = new boolean [2][m+1][n+1][402];
		can[0][0][0][200] = true;
		int best = 0;
		for (int i = 0; i < s.length(); i++) {
			for (int pos = 0; pos <= 400; pos++)
				for (int use = 0; use < n; use++)
					for (int dir = 0; dir < 2; dir++)
						if (can[dir][i][use][pos]) {
							// don't change
							if (s.charAt(i)=='F') {
								int nextpos = pos + (dir == 0 ? 1 : -1);
								int nextuse = use;
								int nextdir = dir;
								int nexti = i+1;
								can [nextdir][nexti][nextuse][nextpos] = true;
							}
							if (s.charAt(i)=='T') {
								int nextpos = pos;
								int nextuse = use;
								int nextdir = dir^1;
								int nexti = i+1;
								can [nextdir][nexti][nextuse][nextpos] = true;
							}
							// change
							if (s.charAt(i)=='F') {
								int nextpos = pos;
								int nextuse = use + 1;
								int nextdir = dir ^ 1;
								int nexti = i+1;
								can [nextdir][nexti][nextuse][nextpos] = true;
							}
							if (s.charAt(i)=='T') {
								int nextpos = pos+ (dir == 0 ? 1 : -1);
								int nextuse = use + 1;
								int nextdir = dir;
								int nexti = i+1;
								can [nextdir][nexti][nextuse][nextpos] = true;
							}

						}
		}
		for (int dir = 0; dir < 2; dir++)
			for (int pos = 0; pos <= 400; pos++)
				for (int use = 0; use <= n; use++)
					if (can[dir][m][use][pos] && (n-use)%2==0) {
						best = max (best, abs(pos - 200));
					}
		out.println(best);
	}

	/********************************************************************************************/
	/* THERE IS INPUT */

	BufferedReader in;
	PrintWriter out;
	StringTokenizer st;

	long stime=0;

	private String next() throws Exception {
		while (st == null || !st.hasMoreElements())
			st = new StringTokenizer(in.readLine());
		return st.nextToken();
	}

	private int nextInt() throws Exception {
		return Integer.parseInt(next());
	}

	private long nextLong() throws Exception {
		return Long.parseLong(next());
	}

	private double nextDouble() throws Exception {
		return Double.parseDouble(next());
	}

	public void run() {
		try {
			//Locale.setDefault(Locale.US);
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(new OutputStreamWriter(System.out));
			solve();
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			out.close();
		}
	}

	public static void main(String[] args) throws Exception {
		new Thread(null, new Solution(), "", 1 << 25).start();
	}

}

import java.util.Scanner;

public class C132 {
	public static void main(String[] args) throws Exception {
		Scanner in = new Scanner(System.in);
		a = in.nextLine();
		n = in.nextInt();
		dp = new int[2][a.length()][n + 1];
		for (int x = 0; x < a.length(); x++) {
			for (int y = 0; y < n + 1; y++) {
				dp[0][x][y] = dp[1][x][y] = NULL;
			}
		}
		int a = max(0, n, 0);
		int b = -max(0, n, 1);
		System.out.println(a > b ? a : b);
	}

	static int max(int start, int swaps, int f) {
		if (swaps < 0)
			return NULL2;
		if(start==a.length()) {
			if(swaps%2==0) return 0;
			else return NULL2;
		}
		if (dp[f][start][swaps] == NULL) {
			int n, k, j;
			if (a.charAt(start) == 'F') {
				k = max(start + 1, swaps, f);
				n = k + 1;
				j = -max(start + 1, swaps - 1, 1 - f);
			} else {
				j = max(start + 1, swaps, 1 - f);
				k = max(start + 1, swaps - 1, f);
				n = k + 1;
			}
			if (k == NULL2 || (j != NULL2 && j > n)) {
				dp[f][start][swaps] = j;
			} else
				dp[f][start][swaps] = n;
		}

		return dp[f][start][swaps];
	}

	static int NULL = 6969;
	static int NULL2 = 696969;
	static String a;
	static int n;
	static int[][][] dp;
}

import java.util.Arrays;
import java.util.Scanner;

public class CF132C {
	private static final int INF = -125000;
	private static String commands;
	private static int[][][] memo;
	public static void main(String[] args) throws Exception {
		Scanner br = new Scanner(System.in);
		commands = br.next();
		int k = br.nextInt();

		memo = new int[commands.length()][k + 1][2];
		for (int i = 0; i < memo.length; i++) {
			for (int j = 0; j < memo[i].length; j++) {
				Arrays.fill(memo[i][j], INF);
			}
		}

		System.out.println(go(0, k, 0));
	}

	private static int go(int index, int k, int direction) {
		if (k < 0) {
			return INF;
		}

		if (index >= commands.length()) {
			if (k > 0) {
				return INF;
			}

			return 0;
		}

		if (memo[index][k][direction] != INF) {
			return memo[index][k][direction];
		}

		int keepNewDirection = commands.charAt(index) == 'F' ? direction : 1 - direction;
		int keepDistance = commands.charAt(index) == 'F' ? 1 : 0;
		if (direction == 1) {
			keepDistance = -keepDistance;
		}

		int keepResult = go(index + 1, k, keepNewDirection) + keepDistance;

		int switchNewDirection = commands.charAt(index) == 'F' ? 1 - direction : direction;
		int switchDistance = commands.charAt(index) == 'F' ? 0 : 1;
		if (direction == 1) {
			keepDistance = -keepDistance;
		}

		int switchResult = go(index + 1, k - 1, switchNewDirection) + switchDistance;

		return memo[index][k][direction] = Math.max(keepResult, switchResult);
	}
}

/*

FT
1

FFFTFFF
2

 */

import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
    static class Reader
    {
        private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
        public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
        public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
        public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
        public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
        public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;}
        public double d() throws IOException {return Double.parseDouble(s()) ;}
        public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
        public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
        public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;}
    }

           //       |----|       /\      |    |   -----   |
           //       |   /       /  \     |    |     |     |
           //       |--/       /----\    |----|     |     |
           //       |   \     /      \   |    |     |     |
           //       |    \   /        \  |    |   -----   -------

    static int cache[][][][][],n;
    static String s;
    public static int dp(int pos,int changed,int dis,int dom,int dir)
    {
        if(pos==s.length())
        {
            if(changed==n)return dis;
            return -1000000000;
        }
        if(changed>n)
        return -1000000000;
        if(cache[pos][changed][dis][dom][dir]!=-1)
        return cache[pos][changed][dis][dom][dir];

        if(s.charAt(pos)=='F')
        {
            int ans=-1000000000;
            if(dir==0)
            {
                if(dom==0)
                ans=dp(pos+1,changed,dis+1,dom,dir);
                else
                {
                    if(dis-1<=0)
                    ans=dp(pos+1,changed,Math.abs(dis-1),dom^1,dir);
                    else
                    ans=dp(pos+1,changed,dis-1,dom,dir);
                }
            }
            else
            {
                if(dom==1)
                ans=dp(pos+1,changed,dis+1,dom,dir);
                else
                {
                    if(dis-1<=0)
                    ans=dp(pos+1,changed,Math.abs(dis-1),dom^1,dir);
                    else
                    ans=dp(pos+1,changed,dis-1,dom,dir);
                }
            }
            return cache[pos][changed][dis][dom][dir]=Math.max(ans,dp(pos+1,changed+1,dis,dom,dir^1));
        }
        else
        {
            int ans=-1000000000;
            if(dir==0)
            {
                if(dom==0)
                ans=dp(pos+1,changed+1,dis+1,dom,dir);
                else
                {
                    if(dis-1<=0)
                    ans=dp(pos+1,changed+1,Math.abs(dis-1),dom^1,dir);
                    else
                    ans=dp(pos+1,changed+1,dis-1,dom,dir);
                }
            }
            else
            {
                if(dom==1)
                ans=dp(pos+1,changed+1,dis+1,dom,dir);
                else
                {
                    if(dis-1<=0)
                    ans=dp(pos+1,changed+1,Math.abs(dis-1),dom^1,dir);
                    else
                    ans=dp(pos+1,changed+1,dis-1,dom,dir);
                }
            }
            return cache[pos][changed][dis][dom][dir]=Math.max(ans,dp(pos+1,changed,dis,dom,dir^1));
        }
    }
    public static void main(String[] args)throws IOException
    {
        PrintWriter out= new PrintWriter(System.out);
        Reader sc=new Reader();
        s=sc.s();
        n=sc.i();
        cache=new int[s.length()][n+1][s.length()+1][2][2];
        for(int i=0;i<s.length();i++)for(int j=0;j<=n;j++)
        for(int k=0;k<=s.length();k++)for(int l=0;l<2;l++)Arrays.fill(cache[i][j][k][l],-1);
        out.println(dp(0,0,0,0,0));
        out.flush();
    }
}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

public class _132C {

  static final int OFFSET = 50;
  static int n;
  static int m;
  static char[] a;
  static Set<Integer>[][][] f;

  @SuppressWarnings("unchecked")
  public static void main(String[] args) throws Exception {
    Reader.init(System.in);
    BufferedWriter cout = new BufferedWriter(new OutputStreamWriter(System.out));

    a = Reader.next().toCharArray();
    n = a.length;
    a = (" " + String.valueOf(a)).toCharArray();
    m = Reader.nextInt();
    f = new HashSet[n + 1][m + 1][2];

    for (int i = 0; i < f.length; i++)
      for (int j = 0; j < f[i].length; j++)
        for (int k = 0; k < f[i][j].length; k++)
          f[i][j][k] = new HashSet<>();

    f[0][0][1].add(0);
    for (int i = 0; i < n; i++)
      for (int j = 0; j <= m; j++)
        for (int k = 0; k < 2; k++) {
          if (a[i + 1] == 'T') {
            for (int pos : f[i][j][k]) {
              f[i + 1][j][1 - k].add(pos);
              if (j < m)
                f[i + 1][j + 1][k].add(pos + (k == 1 ? 1 : -1));
            }
          } else {
            for (int pos : f[i][j][k]) {
              f[i + 1][j][k].add(pos + (k == 1 ? 1 : -1));
              if (j < m)
                f[i + 1][j + 1][1 - k].add(pos);
            }
          }
        }

    int ans = 0;
    for (int dir = 0; dir < 2; dir++)
      for (int pos : f[n][m][dir])
        ans = Math.max(ans, Math.abs(pos));
    System.out.println(ans);
    cout.close();
  }

  static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
    final U _1;
    final V _2;

    private Pair(U key, V val) {
      this._1 = key;
      this._2 = val;
    }

    public static <U extends Comparable<U>, V extends Comparable<V>> Pair<U, V> instanceOf(U _1, V _2) {
      return new Pair<U, V>(_1, _2);
    }

    @Override
    public String toString() {
      return _1 + " " + _2;
    }

    @Override
    public int hashCode() {
      int res = 17;
      res = res * 31 + _1.hashCode();
      res = res * 31 + _2.hashCode();
      return res;
    }

    @Override
    public int compareTo(Pair<U, V> that) {
      int res = this._1.compareTo(that._1);
      if (res < 0 || res > 0)
        return res;
      else
        return this._2.compareTo(that._2);
    }

    @Override
    public boolean equals(Object obj) {
      if (this == obj)
        return true;
      if (!(obj instanceof Pair))
        return false;
      Pair<?, ?> that = (Pair<?, ?>) obj;
      return _1.equals(that._1) && _2.equals(that._2);
    }
  }

  /** Class for buffered reading int and double values */
  static class Reader {
    static BufferedReader reader;
    static StringTokenizer tokenizer;

    /** call this method to initialize reader for InputStream */
    static void init(InputStream input) {
      reader = new BufferedReader(new InputStreamReader(input));
      tokenizer = new StringTokenizer("");
    }

    /** get next word */
    static String next() throws IOException {
      while (!tokenizer.hasMoreTokens()) {
        // TODO add check for eof if necessary
        tokenizer = new StringTokenizer(reader.readLine());
      }
      return tokenizer.nextToken();
    }

    static int nextInt() throws IOException {
      return Integer.parseInt(next());
    }

    static double nextDouble() throws IOException {
      return Double.parseDouble(next());
    }
  }

  static class ArrayUtil {
    static void swap(int[] a, int i, int j) {
      int tmp = a[i];
      a[i] = a[j];
      a[j] = tmp;
    }

    static void swap(long[] a, int i, int j) {
      long tmp = a[i];
      a[i] = a[j];
      a[j] = tmp;
    }

    static void swap(double[] a, int i, int j) {
      double tmp = a[i];
      a[i] = a[j];
      a[j] = tmp;
    }

    static void swap(char[] a, int i, int j) {
      char tmp = a[i];
      a[i] = a[j];
      a[j] = tmp;
    }

    static void swap(boolean[] a, int i, int j) {
      boolean tmp = a[i];
      a[i] = a[j];
      a[j] = tmp;
    }

    static void reverse(int[] a, int i, int j) {
      for (; i < j; i++, j--)
        swap(a, i, j);
    }

    static void reverse(long[] a, int i, int j) {
      for (; i < j; i++, j--)
        swap(a, i, j);
    }

    static void reverse(double[] a, int i, int j) {
      for (; i < j; i++, j--)
        swap(a, i, j);
    }

    static void reverse(char[] a, int i, int j) {
      for (; i < j; i++, j--)
        swap(a, i, j);
    }

    static void reverse(boolean[] a, int i, int j) {
      for (; i < j; i++, j--)
        swap(a, i, j);
    }

    static long sum(int[] a) {
      int sum = 0;
      for (int i : a)
        sum += i;
      return sum;
    }

    static long sum(long[] a) {
      long sum = 0;
      for (long i : a)
        sum += i;
      return sum;
    }

    static double sum(double[] a) {
      double sum = 0;
      for (double i : a)
        sum += i;
      return sum;
    }

    static int max(int[] a) {
      int max = Integer.MIN_VALUE;
      for (int i : a)
        if (i > max)
          max = i;
      return max;
    }

    static int min(int[] a) {
      int min = Integer.MAX_VALUE;
      for (int i : a)
        if (i < min)
          min = i;
      return min;
    }

    static long max(long[] a) {
      long max = Long.MIN_VALUE;
      for (long i : a)
        if (i > max)
          max = i;
      return max;
    }

    static long min(long[] a) {
      long min = Long.MAX_VALUE;
      for (long i : a)
        if (i < min)
          min = i;
      return min;
    }
  }
}

import java.util.Scanner;

public class E {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		int T = 0;
		int L = s.length();
		for (int i = 0; i < L; i++) {
			if (s.charAt(i)=='T')
				T++;
		}

		int n = sc.nextInt();
		if (T <= n) {
			int k = n-T;
			if (k % 2==0)
				System.out.println(L);
			else
				System.out.println(L-1);
			return;
		}
		int[]a = new int[L+1];
		for (int i = 1; i <= L; i++) {
			if (s.charAt(i-1)=='T')
				a[i] = 1;
			a[i] += a[i-1];
		}
		int k = 0, max = 0;
		for (int i = 1; i < L; i++) {
			for (int j = i+1; j <= L; j++) {
				if (a[j]-a[i-1] <= n) {
					if (j-i+1 > max) {
						max = j-i+1;
						k = a[j]-a[i-1];
					}
				}
			}
		}
		if (k % 2==0)
			System.out.println(max);
		else
			System.out.println(max-1);
	}
}

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		int T = 0;
		int L = s.length();
		for (int i = 0; i < L; i++) {
			if (s.charAt(i)=='T')
				T++;
		}

		int n = sc.nextInt();
		if (T <= n) {
			int k = n-T;
			if (k % 2==0)
				System.out.println(L);
			else
				System.out.println(L-1);
			return;
		}
		int[]a = new int[L+1];
		for (int i = 1; i <= L; i++) {
			if (s.charAt(i-1)=='T')
				a[i] = 1;
			a[i] += a[i-1];
		}
		int k = 0, max = 0;
		for (int i = 1; i <= 1; i++) {
			for (int j = i; j <= L; j++) {
				if (a[j]-a[i-1] <= n) {
					if (j-i+1 > max) {
						max = j-i+1;
						k = a[j]-a[i-1];
					}
				}
			}
		}
		if ((max-k) % 2==0)
			System.out.println(max);
		else {
			if (max==L)
				System.out.println(max-1);
			else
				System.out.println(max);
		}
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class LogoTurtle {

	static class Scanner{
		BufferedReader br=null;
		StringTokenizer tk=null;
		public Scanner(){
			br=new BufferedReader(new InputStreamReader(System.in));
		}
		public String next() throws IOException{
			while(tk==null || !tk.hasMoreTokens())
				tk=new StringTokenizer(br.readLine());
			return tk.nextToken();
		}
		public int nextInt() throws NumberFormatException, IOException{
			return Integer.valueOf(next());
		}
		public double nextDouble() throws NumberFormatException, IOException{
			return Double.valueOf(next());
		}
	}

	static Integer[][][][] dp;

	static int dp(int pos, int quedan, int dir, int idx){
		int npos = pos + 100;
		if (dp[npos][quedan][dir][idx] != null)
			return dp[npos][quedan][dir][idx];
		if (idx == commands.length){
			dp[npos][quedan][dir][idx] = (quedan == 0)? Math.abs(pos) : 0;
			return dp[npos][quedan][dir][idx];
		}
		int ret = 0;
		// no change
		if (commands[idx] == 'T')
			ret = dp(pos, quedan, (dir + 1) % 2, idx + 1);
		else{
			int np = ((dir == 0)? pos + 1: pos - 1);
			ret = dp(np, quedan, dir, idx + 1);
		}
		if (quedan == 0){
			dp[npos][quedan][dir][idx] = ret;
			return ret;
		}
		// change
		if (commands[idx] == 'F')
			ret = Math.max(ret, dp(pos, quedan - 1, (dir + 1) % 2, idx + 1));
		else{
			int np = ((dir == 0)? pos + 1: pos - 1);
			ret = Math.max(ret, dp(np, quedan - 1, dir, idx + 1));
		}
		dp[npos][quedan][dir][idx] = ret;
		return ret;
	}

	static char[] commands;
	static int N;

	public static void main(String args[]) throws IOException{
		Scanner sc = new Scanner();
		commands = sc.next().toCharArray();
		N = sc.nextInt();
		dp = new Integer[205][N + 1][2][commands.length + 1];
		System.out.println(dp(0, N, 0, 0));
	}

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class C132 {
	static char[] com;
	static int[][][][] mem;
	public static void main(String[] args) throws IOException{
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

		com = bf.readLine().toCharArray();

		int n = Integer.parseInt(bf.readLine());
		mem = new int[2][2][n+1][com.length];

		for(int[][][] a:mem)
			for(int[][] a2:a)
				for(int[] a3:a2)
					Arrays.fill(a3, -1);

		System.out.println(Math.abs(dp(0,0,n,0)));
	}
	static int dp(int dir, int changed,int n, int idx){
		if(idx==com.length)
			return n==0?0:-(int)1e9;

		if(mem[dir][changed][n][idx]!=-1)
			return mem[dir][changed][n][idx];

		int ans = 0;
		if((com[idx]=='F'&&changed==0)||(com[idx]=='T'&&changed==1))
			if(Math.abs(dp(dir,0,n,idx+1))<=100)
				ans = (dir==0?1:-1)+dp(dir,0,n,idx+1);
		else
			if(Math.abs(dp(dir==0?1:0, 0, n, idx+1))<=100)
				ans = dp(dir==0?1:0, 0, n, idx+1);

		if(n>0&&Math.abs(dp(dir, changed==0?1:0, n-1, idx))>Math.abs(ans)&&Math.abs(dp(dir, changed==0?1:0, n-1, idx))<=100)
			ans = dp(dir, changed==0?1:0, n-1, idx);

		return mem[dir][changed][n][idx] = ans;
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Egor Kulikov (egor@egork.net)
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskC solver = new TaskC();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskC {
	public void solve(int testNumber, InputReader in, OutputWriter out) {
		char[] commands = in.readString().toCharArray();
		int changes = in.readInt();
		boolean[][][] reachable = new boolean[commands.length + 1][2 * commands.length + 1][changes + 1];
		reachable[0][commands.length][changes] = true;
		for (int i = 0; i < commands.length; i++) {
			for (int j = commands.length - i; j <= commands.length + i; j++) {
				for (int k = 0; k <= changes; k++) {
					if (reachable[i][j][k]) {
						if (commands[i] == 'F') {
							reachable[i + 1][j + 1][k] = true;
							if (k != 0)
								reachable[i + 1][2 * commands.length - j][k - 1] = true;
						} else {
							reachable[i + 1][2 * commands.length - j][k] = true;
							if (k != 0)
								reachable[i + 1][j + 1][k - 1] = true;
						}
					}
				}
			}
		}
		int answer = 0;
		for (int i = 0; i <= 2 * commands.length; i++) {
			for (int j = 0; j < changes; j += 2) {
				if (reachable[commands.length][i][j])
					answer = Math.max(answer, Math.abs(i - commands.length));
			}
		}
		out.printLine(answer);
	}
}

class InputReader {

	private InputStream stream;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int numChars;

	public InputReader(InputStream stream) {
		this.stream = stream;
	}

	public int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int readInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public String readString() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuffer res = new StringBuffer();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	public static boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	}

class OutputWriter {
	private final PrintWriter writer;

	public OutputWriter(OutputStream outputStream) {
		writer = new PrintWriter(outputStream);
	}

	public OutputWriter(Writer writer) {
		this.writer = new PrintWriter(writer);
	}

	public void print(Object...objects) {
		for (int i = 0; i < objects.length; i++) {
			if (i != 0)
				writer.print(' ');
			writer.print(objects[i]);
		}
	}

	public void printLine(Object...objects) {
		print(objects);
		writer.println();
	}

	public void close() {
		writer.close();
	}

	}

import java.io.*;
import java.util.*;

public class E {

    boolean DP[][][][];

    public boolean contains_printing_char(String s) {
	for (int i=0; i<s.length(); i++) {
	    if (s.charAt(i) == 'H' || s.charAt(i) =='Q' || s.charAt(i) =='9') return true;
	}
	return false;
    }

    public void read_input_and_solve() throws IOException {
	Scanner sc = new Scanner(System.in);
	String p = sc.nextLine();
	int changes = sc.nextInt();
	int n = p.length();
	DP = new boolean[n+1][2*n+1][changes+1][2];
	DP[0][n][0][0] = true;
	for (int t=1; t<=n; t++) {
	    char ch = p.charAt(t-1);
	    for (int h=0; h<=2*n; h++) {
		for (int c=0; c<=changes; c++) {
		    for (int dir=0; dir<2; dir++) {
			/* assign DP[t][h][c][dir] */
			boolean ans = false;
			int cc;
			if (ch=='T') cc=c; else cc=c-1;
			if (cc>=0) ans = ans || (DP[t-1][h][cc][1-dir]);

			if (ch=='F') cc=c; else cc=c-1;
			int ph = h + 1 - 2*dir;
			if (cc>=0 && ph>=0 && ph<=2*n) ans = ans || (DP[t-1][ph][cc][dir]);
			DP[t][h][c][dir] = ans;

			/*
			System.out.printf("DP[%d][%d][%d][%d] = %B\n", t, h, c, dir, ans);
			*/
		    }
		}
	    }
	}
	int maxd = 0;
	for (int h=0; h<=2*n; h++) {
	    for (int dir=0; dir<2; dir++) {
		if (DP[n][h][changes][dir]) maxd = Math.max(maxd, (Math.abs(h-n)));
	    }
	}
	System.out.println(maxd);
    }

    public static void main(String[] args) throws IOException {
	(new E()).read_input_and_solve();
    }
}

import java.io.*;
import java.util.Locale;
import java.util.StringTokenizer;

public class A implements Runnable {

    private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

    private BufferedReader in;
    private PrintWriter out;
    private StringTokenizer tok = new StringTokenizer("");

    private void init() throws FileNotFoundException {
        Locale.setDefault(Locale.US);
        String fileName = "";
        if (ONLINE_JUDGE && fileName.isEmpty()) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        } else {
            if (fileName.isEmpty()) {
                in = new BufferedReader(new FileReader("input.txt"));
                out = new PrintWriter("output.txt");
            } else {
                in = new BufferedReader(new FileReader(fileName + ".in"));
                out = new PrintWriter(fileName + ".out");
            }
        }
    }

    String readString() {
        while (!tok.hasMoreTokens()) {
            try {
                tok = new StringTokenizer(in.readLine());
            } catch (Exception e) {
                return null;
            }
        }
        return tok.nextToken();
    }

    int readInt() {
        return Integer.parseInt(readString());
    }

    long readLong() {
        return Long.parseLong(readString());
    }

    double readDouble() {
        return Double.parseDouble(readString());
    }

    int[] readIntArray(int size) {
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = readInt();
        }
        return a;
    }

    public static void main(String[] args) {
        //new Thread(null, new A(), "", 128 * (1L << 20)).start();
        new A().run();
    }

    long timeBegin, timeEnd;

    void time() {
        timeEnd = System.currentTimeMillis();
        System.err.println("Time = " + (timeEnd - timeBegin));
    }

    @Override
    public void run() {
        try {
            timeBegin = System.currentTimeMillis();
            init();
            solve();
            out.close();
            time();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    final int OFFSET = 100;
    final int MAX_ANSWER = 200;

    void solve() throws IOException {
        char[] s = readString().toCharArray();
        int n = readInt();
        boolean[][][][] dp = new boolean[s.length + 1][n + 1][2][MAX_ANSWER + 1];
        dp[0][0][0][OFFSET] = true;
        for (int i = 1; i <= s.length; i++) {
            for (int j = 0; j < n; j++) {
                for (int d = 0; d < MAX_ANSWER; d++) {
                    if (dp[i - 1][j][0][d]) {
                        if (s[i - 1] == 'T') {
                            for (int changes = j; changes <= n; changes++) {
                                if (j % 2 == changes % 2) {
                                    dp[i][changes][1][d] = true;
                                } else {
                                    dp[i][changes][0][d + 1] = true;
                                }
                            }
                        } else {
                            for (int changes = j; changes <= n; changes++) {
                                if (j % 2 == changes % 2) {
                                    dp[i][changes][0][d + 1] = true;
                                } else {
                                    dp[i][changes][1][d] = true;
                                }
                            }
                        }
                    }

                    if (dp[i - 1][j][1][d]) {
                        if (s[i - 1] == 'T') {
                            for (int changes = j; changes <= n; changes++) {
                                if (j % 2 == changes % 2) {
                                    dp[i][changes][0][d] = true;
                                } else {
                                    dp[i][changes][1][d - 1] = true;
                                }
                            }
                        } else {
                            for (int changes = j; changes <= n; changes++) {
                                if (j % 2 == changes % 2) {
                                    dp[i][changes][1][d - 1] = true;
                                } else {
                                    dp[i][changes][0][d] = true;
                                }
                            }
                        }
                    }
                }
            }
        }
        int answer = 0;
        for (int d = 0; d <= MAX_ANSWER; d++) {
            if (dp[s.length][n][0][d] || dp[s.length][n][1][d]) {
                answer = Math.max(answer, Math.abs(OFFSET - d));
            }
        }
        out.println(answer);
    }
}

import java.io.*;
import java.util.*;

public class C {

	public C () throws IOException {
		char [] commands = sc.next().toCharArray();
		int N = sc.nextInt();
		solve(commands, N);
	}

	public void solve (char [] C, int N) {

		int L = C.length;
		while (N > 0) {
			// 1. All Fs
			String cmd = new String(C);
			if (cmd.indexOf('T') == -1) {
				C[0] = 'T';
				--N;
			}

			// 2. N == 1
			else if (N == 1) {
				int S = -1;
				for (int i = 0; i < L; ++i) {
					C[i] = ch(C[i]);
					S = Math.max(S, eval(C));
					C[i] = ch(C[i]);
				}
				print(S);
			}

			else {
				int count = 0;
				for (int i = 0; i < L; ++i) {
					if (C[i] == 'T')
						++count;
				}

				// 3. N >= 2, just one T
				if (count == 1) {
					for (int i = 0; i < L; ++i) {
						if (C[i] == 'T')
							C[i] = 'F';
					}
					--N;
				} else {
					int S = 0, x = -1, y = -1, z = -1;
					for (int i = 0; i < L; ++i) {
						for (int j = i+1; j < L; ++j)
							if (C[i] == 'T' && C[j] == 'T') {
								C[i] = ch(C[i]); C[j] = ch(C[j]);
								int E = eval(C);
								if (E >= S) {
									S = E; x = i; y = j;
								}
								C[i] = ch(C[i]); C[j] = ch(C[j]);
						}
						if (C[i] == 'T') {
							C[i] = ch(C[i]);
							int E = eval(C);
							if (E >= S) {
								S = E; z = i;
							}
							C[i] = ch(C[i]);
						}
					}
					if (z >= 0) {
						C[z] = 'F'; --N;
					} else {
						C[x] = C[y] = 'F'; N -= 2;
					}
				}
			}
		}

		print (eval(C));
	}

	int eval (char [] C) {
		int x = 0, d = 1;
		for (char c : C) {
			if (c == 'T')
				d = -d;
			if (c == 'F')
				x += d;
		}
		return Math.abs(x);
	}

	char ch (char X) {
		if (X == 'F') return 'T';
		else return 'F';
	}

	////////////////////////////////////////////////////////////////////////////////////

	static Scanner sc;
	static long t;

	static void print2 (Object o) {
		System.out.println(o);
	}

	static void print (Object o) {
		print2(o);
		//print2((millis() - t) / 1000.0);
		System.exit(0);
	}

	static void run () throws IOException {
		sc = new Scanner(System.in);
		new C();
	}

	public static void main(String[] args) throws IOException {
		run();
	}

	static long millis() {
		return System.currentTimeMillis();
	}
}

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String s = in.next();
		int n = in.nextInt();
		int t;
		char[] tmp;
		int max = -1;
		int r;
		for (int i = 0; i < s.length(); i++) {
			tmp = s.toCharArray();
			t = n;
			for (int j = i; j < s.length(); j++) {
				if (tmp[j] == 'T') {
					t--;
					tmp[j] = 'F';
				}
				if (t == 0)
					break;
			}
			r = getMax(tmp);
			if (t != 0) {
				if (r == tmp.length) {
					if (t % 2 != 0)
						r--;
				}
			}
			max = Math.max(max, r);
		}
		System.out.println(max);
	}

	public static int getMax(char[] a) {
		int cnt = 0;
		boolean f = true;
		for (int i = 0; i < a.length; i++) {
			if (a[i] == 'F') {
				if (f)
					cnt++;
				else
					cnt--;
			} else {
				f = !f;
			}
		}
		return Math.abs(cnt);
	}
}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class cf132c {
  static int n,m,oo=987654321;;
  static String v;
  static Integer[][][] memo;
  public static void main(String[] args) {
    FastIO in = new FastIO(), out = in;
    v = in.next().trim();
    n = in.nextInt();
    m = v.length();
    memo = new Integer[2][m][n+1];
    out.println(Math.max(go(0,n,0),go(0,n,1)));
    out.close();
  }
  static int go(int pos, int left, int dir) {
    if(left < 0) return -oo;
    if(pos == m) {
      return left==0?0:-oo;
    }
    if(memo[dir][pos][left] != null)
      return memo[dir][pos][left];
    int ans = -oo;
    char comm = v.charAt(pos);
    ans = Math.max(ans, go(pos+1,left-(comm=='T'?0:1),1-dir));
    ans = Math.max(ans, 2*dir-1 + go(pos+1,left-(comm=='F'?0:1),dir));
    return memo[dir][pos][left] = ans;
  }
  static class FastIO extends PrintWriter {
    BufferedReader br;
    StringTokenizer st;

    public FastIO() {
      this(System.in,System.out);
    }
    public FastIO(InputStream in, OutputStream out) {
      super(new BufferedWriter(new OutputStreamWriter(out)));
      br = new BufferedReader(new InputStreamReader(in));
      scanLine();
    }
    public void scanLine() {
      try {
        st = new StringTokenizer(br.readLine().trim());
      } catch(Exception e) {
        throw new RuntimeException(e.getMessage());
      }
    }
    public int numTokens() {
      if(!st.hasMoreTokens()) {
        scanLine();
        return numTokens();
      }
      return st.countTokens();
    }
    public String next() {
      if(!st.hasMoreTokens()) {
        scanLine();
        return next();
      }
      return st.nextToken();
    }
    public double nextDouble() {
      return Double.parseDouble(next());
    }
    public long nextLong() {
      return Long.parseLong(next());
    }
    public int nextInt() {
      return Integer.parseInt(next());
    }
  }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TreeSet;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            String commands = in.next();
            int n = in.nextInt();
            TreeSet<state> states = new TreeSet<>();
            state zero = new state();
            zero.dir = 1;
            zero.dist = 0;
            states.add(zero);
            for (int i = 0; i < commands.length(); i++) {
                TreeSet<state> nextStates = new TreeSet<>();
                for (state cur : states) {
                    if (commands.charAt(i) == 'T') {
                        state next = cur.copy();
                        next.dir = -next.dir;
                        nextStates.add(next);
                        if (cur.change < n) {
                            next = cur.copy();
                            next.change++;
                            next.dist += next.dir;
                            nextStates.add(next);
                        }
                    }
                    if (commands.charAt(i) == 'F') {
                        state next = cur.copy();
                        next.dist += next.dir;
                        nextStates.add(next);
                        if (cur.change < n) {
                            next = cur.copy();
                            next.change++;
                            next.dir = -next.dir;
                            nextStates.add(next);
                        }
                    }
                }
                states = nextStates;
            }
            int ans = 0;
            for (state cur : states) {
                if (cur.change == n && Math.abs(cur.dist) > ans) {
                    ans = Math.abs(cur.dist);
                }
            }
            out.println(ans);
        }

    }

    static class state implements Comparable {
        int dir;
        int dist;
        int change;

        public int compareTo(Object o) {
            state other = (state) o;
            if (other.change != change) return other.change - change;
            if (other.dist != dist) return other.dist - dist;
            if (other.dir != dir) return other.dir - dir;
            return 0;
        }

        state copy() {
            state res = new state();
            res.dir = dir;
            res.dist = dist;
            res.change = change;
            return res;
        }

    }

    static class InputReader {
        private BufferedReader reader;
        private StringTokenizer stt;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream));
        }

        public String nextLine() {
            try {
                return reader.readLine();
            } catch (IOException e) {
                return null;
            }
        }

        public String next() {
            while (stt == null || !stt.hasMoreTokens()) {
                stt = new StringTokenizer(nextLine());
            }
            return stt.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.io.*;
import java.util.*;

public class C {

	public C () throws IOException {
		char [] commands = sc.next().toCharArray();
		int N = sc.nextInt();
		solve(commands, N);
	}

	public void solve (char [] C, int N) {

		int L = C.length;
		while (N > 0) {
			// 1. All Fs
			String cmd = new String(C);
			if (cmd.indexOf('T') == -1) {
				C[0] = 'T';
				--N;
			}

			// 2. N == 1
			else if (N == 1) {
				int S = -1;
				for (int i = 0; i < L; ++i) {
					C[i] = ch(C[i]);
					S = Math.max(S, eval(C));
					C[i] = ch(C[i]);
				}
				print(S);
			}

			else {
				int count = 0;
				for (int i = 0; i < L; ++i) {
					if (C[i] == 'T')
						++count;
				}

				// 3. N >= 2, just one T
				if (count == 1) {
					for (int i = 0; i < L; ++i) {
						if (C[i] == 'T')
							C[i] = 'F';
					}
					--N;
				} else {
					int S = 0, x = -1, y = -1;
					for (int i = 0; i < L; ++i) {
						for (int j = i+1; j < L; ++j)
							if (C[i] == 'T' && C[j] == 'T') {
								C[i] = ch(C[i]); C[j] = ch(C[j]);
								int E = eval(C);
								if (E >= S) {
									S = E; x = i; y = j;
								}
								C[i] = ch(C[i]); C[j] = ch(C[j]);
						}
					}
					C[x] = C[y] = 'F'; N -= 2;
				}
			}
		}

		print (eval(C));
	}

	int eval (char [] C) {
		int x = 0, d = 1;
		for (char c : C) {
			if (c == 'T')
				d = -d;
			if (c == 'F')
				x += d;
		}
		return Math.abs(x);
	}

	char ch (char X) {
		if (X == 'F') return 'T';
		else return 'F';
	}

	////////////////////////////////////////////////////////////////////////////////////

	static Scanner sc;
	static long t;

	static void print2 (Object o) {
		System.out.println(o);
	}

	static void print (Object o) {
		print2(o);
		//print2((millis() - t) / 1000.0);
		System.exit(0);
	}

	static void run () throws IOException {
		sc = new Scanner(System.in);
		new C();
	}

	public static void main(String[] args) throws IOException {
		run();
	}

	static long millis() {
		return System.currentTimeMillis();
	}
}

import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Fantast
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		Scanner in = new Scanner(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskE solver = new TaskE();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskE {
    int n;
    char[] s;
    public void solve(int testNumber, Scanner in, PrintWriter out) {
        s = in.next().toCharArray();
        n = in.nextInt();

        for (int i = 0; i < 101; ++i) {
            for (int j = 0; j < 2; ++j) {
                for (int k = 0; k < 101; ++k) {
                    mxs[i][j][k] = -1;
                    mns[i][j][k] = -1;
                }
            }
        }

        out.println(
                mx(
                        Math.abs(mxdist(0, 1, n)),
                        Math.abs(mndist(0, 1, n)),
                        Math.abs(mxdist(0, -1, n)),
                        Math.abs(mndist(0, -1, n))
                ));
    }

    private int mx(int... a) {
        int res = a[0];
        for (int n : a) {
            res = Math.max(res, n);
        }
        return res;
    }

    int mxs[][][] = new int[101][2][101];
    public int mxdist(int ind, int dir, int tochange) {
        if (tochange > s.length - ind || tochange < 0) {
            return Integer.MIN_VALUE / 2;
        }

        if (ind == s.length) {
            return 0;
        }

        int di = (dir+1)/2;
        if (mxs[ind][di][tochange] != -1) {
            return mxs[ind][di][tochange];
        }

        int res;
        if (s[ind] == 'T') {
            res = Math.max(
                    mxdist(ind + 1, -dir, tochange),
                    dir + mxdist(ind + 1, dir, tochange - 1));
        } else {
            res = Math.max(
                    dir + mxdist(ind + 1, dir, tochange),
                    mxdist(ind + 1, -dir, tochange - 1));
        }

        return mxs[ind][di][tochange] = res;
    }

    int mns[][][] = new int[101][2][101];
    public int mndist(int ind, int dir, int tochange) {
        if (tochange > s.length - ind || tochange < 0) {
            return Integer.MAX_VALUE / 2;
        }

        if (ind == s.length) {
            return 0;
        }

        int di = (dir+1)/2;
        if (mns[ind][di][tochange] != -1) {
            return mns[ind][di][tochange];
        }

        int res;
        if (s[ind] == 'T') {
            res = Math.min(
                    mndist(ind + 1, -dir, tochange),
                    dir + mndist(ind + 1, dir, tochange - 1));
        } else {
            res = Math.min(
                    dir + mndist(ind + 1, dir, tochange),
                    mndist(ind + 1, -dir, tochange - 1));
        }

        return mns[ind][di][tochange] = res;
    }
}

import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.image.AreaAveragingScaleFilter;
import static java.lang.Math.*;
import java.lang.*;

public class Main{
    static FastScanner in;
    static PrintWriter out;
    final static boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

    public static void main(String[] args) throws FileNotFoundException {
        Locale.setDefault(Locale.US);

        if (ONLINE_JUDGE){
            in = new FastScanner(System.in);
            out = new PrintWriter(System.out);
        }else{
            in = new FastScanner(new File("input.txt"));
            out = new PrintWriter(new File("output.txt"));
        }

        Task solver = new Task();
        solver.solve(1, in, out);
        out.close();
    }

}

class Task {
    final int N = 110;
    final int Inf = 1000000007;
    String S;
    int n;
    int B=0, aa=0;
    int m;
    int dp[][][] = new int[N][52][2];
    int ans=0;
    //Time Complexity must be O(N*N*M*2) ~ O(N*N*N)
    public final int calc(int pos, int remain, int s) {
        if (remain < 0) return -1000000000;
        if (pos == n && remain > 0) return -1000000000;
        if (pos == n && remain == 0) return 0;

        if (dp[pos][remain][s]!=0) return dp[pos][remain][s];
        char c = S.charAt(pos);

        int p=0;
        if (c=='F') p = max(p, calc(pos+1, remain, s )+(s==1 ? -1 : 1));
         else {
            p = max(p, calc(pos+1, remain, s^1));
            p = max(p, calc(pos+1, remain-1, s)+(s==1 ? -1 : 1));
        }

        //out.println(pos+" "+len+" "+remain+" "+s+" = "+p);
        //if (remain % 2==m % 2) ans = Math.max(ans, p);
        dp[pos][remain][s]=p;
        return p;
    }

    public void solve(int testNumber, FastScanner in, PrintWriter out) {
        S = in.next();
        n = S.length();
        m = in.nextInt();
        boolean existsT = false;

        for (int i=1; i<=n; i++){
            char c = S.charAt(i-1);
            //for (int j)
            if (c=='T') existsT = true;
        }

        {
            ans = Math.max(ans, calc(0, m, 0));
            for (int i=0; i<n; i++)
                for (int j=0; j<=m; j++)
                    for (int np=0; np<=1; np++)
                    if (j % 2==m % 2) ans = Math.max(ans, calc(i, j, np));
            out.println(ans);
        }

    }

}

class Pair implements Comparable<Pair>{
    public int first, second;
    Pair(){
        first=second=-1;
    }
    Pair(int a, int b){
        first = a; second=b;
    }
    @Override
    public int compareTo(Pair b){
        if (first<b.first) return 1; else
        if (first>b.first) return -1; else
        if (second<b.second)  return 1; else return -1;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        char c = (char)42;
        result = (int)(1L*first*second + first + second);
        if (second!=0) result+=first % second;
        if (first!=0) result+=second%first;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        Pair b = (Pair)obj;
        if (first==b.first && second==b.second) return true;
        return false;
    }

}

class PairComparator implements Comparator<Pair>{

    public int compare(Pair a, Pair b) {
        if (a.first<b.first) return 1; else
        if (a.first>b.first) return -1; else
        if (a.second<b.second)  return 1; else return -1;
    }
}

class FastScanner {
    BufferedReader br;
    StringTokenizer st;

    public FastScanner(File f) {
        try {
            br = new BufferedReader(new FileReader(f));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public FastScanner(InputStream f) {
        br = new BufferedReader(new InputStreamReader(f));
    }

    String next() {
        while (st == null || !st.hasMoreTokens()) {
            String s = null;
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (s == null)
                return null;
            st = new StringTokenizer(s);
        }
        return st.nextToken();
    }

    boolean hasMoreTokens() {
        while (st == null || !st.hasMoreTokens()) {
            String s = null;
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (s == null)
                return false;
            st = new StringTokenizer(s);
        }
        return true;
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }
}

import java.io.*;

public class B {
      private static StreamTokenizer in = null;
    private static PrintWriter out = null;

    static int nextInt() throws IOException {
        in.nextToken();
        return (int) in.nval;
    }

    static long nextLong() throws IOException {
        in.nextToken();
        return (long) in.nval;
    }

    static double nextDouble() throws IOException {
        in.nextToken();
        return (double) in.nval;
    }

    static String nextString() throws IOException {
        in.nextToken();
        return in.sval;
    }

    public static void main(String[] args) throws IOException {
        in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        out = new PrintWriter(System.out);
        // Here is the solution:
        String str = nextString();
        int n = nextInt();
        out.println(new B().solve(str, n));
        out.flush();
    }

    String string;
    private int doit(int p, int c, boolean d) {
        if (c < 0)
            return -1;
        if (p == 0) {
            if (c % 2 == 0)
                return 0;
            else
                return -1;
        }

        if (visit[p][c][d?0:1])
            return dp[p][c][d?0:1];

        int res = -1;
        if (string.charAt(p-1) == 'F') {
            res = Math.max(Math.abs(doit(p - 1, c, d) + (d ? 1 : -1)), doit(p - 1, c - 1, !d));
        } else {
            res = Math.max(Math.abs(doit(p - 1, c - 1, d) + (d ? 1 : - 1)), doit(p - 1, c, !d));
        }

        visit[p][c][(d?0:1)] = true;
        return dp[p][c][d?0:1] = res;
    }

    boolean[][][] visit;
    int[][][] dp;
    public int solve(String str, int n) {
        this.string = str;
        int len = str.length();
        visit = new boolean[len+1][n+1][2];
        dp = new int[len+1][n+1][2];
        return Math.max(doit(len, n, true), doit(len, n, false));
    }
}

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.lang.Long;

public class Test {
	static long mod = 1000000007;
	static int[][][][] dp;
	static boolean[][][][]check;
	static int contains;

	public static void main(String[] args) throws FileNotFoundException {
		PrintWriter out = new PrintWriter(System.out);
		Scanner in = new Scanner();
		String line = in.next();
		int n = in.nextInt();
		dp = new int[2][2][n + 1][line.length()];
		check = new boolean[2][2][n + 1][line.length()];
		int val = cal1(0,n,0,line);
		out.println(val);
		out.close();
	}

	public static int cal1(int dir, int left, int index, String line) {
		if (left == 0) {
			return dist(index, line);
		}
		if (index + 1 == line.length()) {
			if (left % 2 == 0) {
				return dist(index, line);
			} else {
				if (line.charAt(index) == 'T') {
					return 1;
				} else {
					return 0;
				}
			}
		}
		if(check[0][dir][left][index]){
			return dp[0][dir][left][index];
		}
		check[0][dir][left][index] = true;

		int result = Integer.MIN_VALUE;
		for (int i = 0; i <= left; i++) {
			if (i % 2 == 0) {
				if (line.charAt(index) == 'T') {
					int a = cal2(1 - dir, left - i, index + 1, line);
					result = Math.max(result, -a);
				} else {
					int tmp = 1 + cal1(dir, left - i, index + 1, line);
					result = Math.max(result, tmp);
				}
			} else {
				if (line.charAt(index) != 'T') {
					int a = cal2(1 - dir, left - i, index + 1, line);
					result = Math.max(result, -a);
				} else {
					int tmp = 1 + cal1(dir, left - i, index + 1, line);
					result = Math.max(result, tmp);
				}
			}
		}
		return dp[0][dir][left][index] = result;
	}

	public static int cal2(int dir, int left, int index, String line) {
		if (left == 0) {
			return dist(index, line);
		}
		if (index + 1 == line.length()) {
			if (left % 2 == 0) {
				return dist(index, line);
			} else {
				if (line.charAt(index) == 'T') {
					return 1;
				} else {
					return 0;
				}
			}
		}
		if(check[1][dir][left][index]){
			return dp[1][dir][left][index];
		}
		check[1][dir][left][index] = true;
		int result = Integer.MAX_VALUE;
		for (int i = 0; i <= left; i++) {
			if (i % 2 == 0) {
				if (line.charAt(index) == 'T') {
					int a = cal1(1 - dir, left - i, index + 1, line);
					result = Math.min(result, -a);
				} else {
					int tmp = 1 + cal1(dir, left - i, index + 1, line);
					result = Math.min(result, tmp);
				}
			} else {
				if (line.charAt(index) != 'T') {
					int a = cal1(1 - dir, left - i, index + 1, line);
					result = Math.min(result, -a);
				} else {
					int tmp = 1 + cal1(dir, left - i, index + 1, line);
					result = Math.min(result, tmp);
				}
			}
		}
		return dp[1][dir][left][index] = result;
	}

	public static int dist(int index, String line) {
		int mul = 1;
		int result = 0;
		for (int i = index; i < line.length(); i++) {
			if (line.charAt(i) == 'T') {
				mul *= -1;
			} else {
				result += mul;
			}
		}
		return result;
	}

	static class Name implements Comparable<Name> {
		String name;
		int h;

		public Name(String name, int h) {
			super();
			this.name = name;
			this.h = h;
		}

		public int compareTo(Name o) {

			return h - o.h;
		}

	}

	static int find(int index, int[] u) {
		if (u[index] != index) {
			return u[index] = find(u[index], u);
		}
		return index;
	}

	static int crossProduct(Point a, Point b) {
		return a.x * b.y + a.y * b.x;
	}

	static long squareDist(Point a) {
		long x = a.x;
		long y = a.y;
		return x * x + y * y;
	}

	static Point minus(Point a, Point b) {
		return new Point(a.x - b.x, a.y - b.y);
	}

	public static boolean nextPer(int[] data) {
		int i = data.length - 1;
		while (i > 0 && data[i] < data[i - 1]) {
			i--;
		}
		if (i == 0) {
			return false;
		}
		int j = data.length - 1;
		while (data[j] < data[i - 1]) {
			j--;
		}
		int temp = data[i - 1];
		data[i - 1] = data[j];
		data[j] = temp;
		Arrays.sort(data, i, data.length);
		return true;
	}

	static class Point {
		int x, y;

		public Point(int x, int y) {
			super();
			this.x = x;
			this.y = y;
		}

		public String toString() {
			return "{" + x + " " + y + "}";
		}

	}

	static class Entry implements Comparable<Entry> {
		int x, cost;

		public Entry(int x, int cost) {
			super();
			this.x = x;
			this.cost = cost;
		}

		public int compareTo(Entry o) {
			// TODO Auto-generated method stub
			if (cost > o.cost) {
				return 1;
			} else if (cost == o.cost) {
				return -1;
			}

			return 0;
		}
	}

	static int gcd(int a, int b) {
		if (b == 0) {
			return a;
		}
		return gcd(b, a % b);
	}

	static class Scanner {

		BufferedReader br;
		StringTokenizer st;

		public Scanner() throws FileNotFoundException {
			// System.setOut(new PrintStream(new
			// BufferedOutputStream(System.out), true));
			br = new BufferedReader(new InputStreamReader(System.in));
			// br = new BufferedReader(new InputStreamReader(new
			// FileInputStream(new File("B-large.in"))));
		}

		public String next() {

			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception e) {
					throw new RuntimeException();
				}
			}
			return st.nextToken();
		}

		public long nextLong() {
			return Long.parseLong(next());
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}

		public double nextDouble() {
			return Double.parseDouble(next());
		}

		public String nextLine() {
			st = null;
			try {
				return br.readLine();
			} catch (Exception e) {
				throw new RuntimeException();
			}
		}

		public boolean endLine() {
			try {
				String next = br.readLine();
				while (next != null && next.trim().isEmpty()) {
					next = br.readLine();
				}
				if (next == null) {
					return true;
				}
				st = new StringTokenizer(next);
				return st.hasMoreTokens();
			} catch (Exception e) {
				throw new RuntimeException();
			}
		}
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class C132 {
	static char[] com;
	static int[][][][] mem;
	public static void main(String[] args) throws IOException{
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

		com = bf.readLine().toCharArray();

		int n = Integer.parseInt(bf.readLine());
		mem = new int[2][2][n+1][com.length];

		for(int[][][] a:mem)
			for(int[][] a2:a)
				for(int[] a3:a2)
					Arrays.fill(a3, -1);

		System.out.println(Math.abs(dp(0,0,n,0)));
	}
	static int dp(int dir, int changed,int n, int idx){
		if(idx==com.length)
			return n==0?0:-(int)1e9;

		if(mem[dir][changed][n][idx]!=-1)
			return mem[dir][changed][n][idx];

		int ans = 0;
		if((com[idx]=='F'&&changed==0)||(com[idx]=='T'&&changed==1))
		{
			if(Math.abs(dp(dir,0,n,idx+1))<=1000)
				ans = (dir==0?1:-1)+dp(dir,0,n,idx+1);
		}
		else
		{
			if(Math.abs(dp(dir==0?1:0, 0, n, idx+1))<=1000)
				ans = dp(dir==0?1:0, 0, n, idx+1);
		}

		if(n>0&&Math.abs(dp(dir, changed==0?1:0, n-1, idx))>Math.abs(ans)&&Math.abs(dp(dir, changed==0?1:0, n-1, idx))<=1000)
			ans = dp(dir, changed==0?1:0, n-1, idx);

		return mem[dir][changed][n][idx] = ans;
	}
}

import java.io.*;
import java.util.*;

/**
 * Created by VIET ANH on 27/04/2015.
 */
public class test {

    private static int T;
    private static long oo=Long.MAX_VALUE;
    private static int base=1000000007;
    private static int[][][] f;
    private static boolean[][][] dau;

    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        String s=in.next();
        int n=in.nextInt();
        f = new int[s.length() + 1][n + 1][2];
        dau = new boolean[s.length() + 1][n + 1][2];
        for (int i = 0; i < s.length() + 1; i++) {
            for (int j = 0; j < n + 1; j++) {
                for (int k = 0; k < 2; k++) {
                    f[i][j][k] = Integer.MIN_VALUE;
                }
            }
        }
        int res=Math.max(Math.abs(solve(s.length(), n, 1, s)), Math.abs(solve(s.length(), n, 0, s)));
        out.print(res);
        out.close();
    }

    private static int solve(int i, int n, int dir, String s) {
        if (i==0) {
            if (n==0&&dir==1) return 0;
            return Integer.MIN_VALUE;
        }
        if (dau[i][n][dir]) return f[i][n][dir];
        char c=s.charAt(i-1);
        int res=Integer.MIN_VALUE;
        for (int j = 0; j <= n; j++) {
            int x = j & 1;
            char c2 = "FT".charAt(("FT".indexOf(c) + x) & 1);
            if (c2=='T') {
                int y=solve(i-1,n-j,1-dir,s);
                if (y!=Integer.MIN_VALUE) {
                    if (res==Integer.MIN_VALUE) res=y;
                    else if (Math.abs(res)<Math.abs(y)) res=y;
                }
            }
            else {
                int y = solve(i - 1, n - j, dir, s);
                if (y!=Integer.MIN_VALUE) {
                    y+=((dir == 1) ? 1 : -1);
                    if (res==Integer.MIN_VALUE) res=y;
                    else if (Math.abs(res)<Math.abs(y)) res=y;
                }
            }
        }
        f[i][n][dir] = res;
        dau[i][n][dir]=true;
        return res;
    }
}

import java.util.*;
public class C {
	static int [] reverse = new int [257];
	static int [][][] dp = new int [105][105][2];
	static char [] path;
	static int MIN_VAL = -(1<<20);
	public static void main (String [] arg) {
		Scanner sc = new Scanner(System.in);
		path = sc.next().toCharArray();
		int n = sc.nextInt();

		for (int i = 0; i<dp.length; ++i) for (int j = 0; j<dp[0].length; ++j) Arrays.fill(dp[i][j], MIN_VAL);
		int ans = recurse(n, 0, 1);
		System.out.println(ans);
	}
	public static int recurse(int n, int pos, int orientation) {
		//System.err.println("@ " + n + " , " + pos + " , " + orientation);
		if (dp[n][pos][orientation] > MIN_VAL+1) return dp[n][pos][orientation];
		if (pos >= path.length) return ( n%2 == 0) ? 0 : MIN_VAL;
		int dir = (orientation == 0) ? -1 : 1;

		int best = MIN_VAL;
		if (n != 0) {
			if (path[pos] == 'F') best = Math.max(best, recurse(n-1, pos+1, 1-orientation));
			if (path[pos] == 'T') best = Math.max(best, dir + recurse(n-1, pos+1, orientation));
		}
		if (path[pos] == 'T') best = Math.max(best, recurse(n, pos+1, 1-orientation));
		if (path[pos] == 'F') best = Math.max(best, dir + recurse(n, pos+1, orientation));
		dp[n][pos][orientation] = best;
		return best;
	}

}

import java.util.Arrays;
import java.util.Scanner;

public class F {
    static int[][][][] dp = new int[110][230][110][3];
    static String inp;

    public static int min(int index, int pos, int n, int direction) {
        if (index == inp.length() && n == 0)
            return Math.abs(pos);
        else if (index == inp.length())
            return Integer.MIN_VALUE;
        else if (dp[index][pos + 100][n][direction + 1] != -1)
            return dp[index][pos + 100][n][direction + 1];
        else {
            if (n == 0) {
                if (inp.charAt(index) == 'T') {
                    return dp[index][pos + 100][n][direction + 1] = min(
                            index + 1, pos, n, -direction);
                } else
                    return dp[index][pos + 100][n][direction + 1] = min(
                            index + 1, pos + direction, n, direction);
            }

            else {
                if (inp.charAt(index) == 'T')
                    return dp[index][pos + 100][n][direction + 1] = Math.max(
                            min(index + 1, pos + direction, n - 1, direction),
                            min(index + 1, pos, n, -direction));
                else {
                    return dp[index][pos + 100][n][direction + 1] = Math.max(
                            min(index + 1, pos + direction, n, direction),
                            (min(index + 1, pos, n - 1, -direction)));
                }
            }
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        inp = in.nextLine();

        int n = in.nextInt();
        for (int i = 0; i < dp.length; i++)
            for (int j = 0; j < dp[i].length; j++)
                for (int k = 0; k < dp[i][j].length; k++)
                    Arrays.fill(dp[i][j][k], -1);
        System.out.println(min(0, 0, n, 1));
    }
}

import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.image.AreaAveragingScaleFilter;
import static java.lang.Math.*;
import java.lang.*;

public class Main {
    static FastScanner in;
    static PrintWriter out;
    public static void main(String[] args) throws FileNotFoundException {
        runIO(0);

        Task solver = new Task();
        solver.solve(1, in, out);
        out.close();
    }

    public static void runIO(int R) throws FileNotFoundException{
        if (R==1){
            in = new FastScanner(new File("input.txt"));
            out = new PrintWriter(new File("output.txt"));
        } else
        {
            in = new FastScanner(System.in);
            out = new PrintWriter(System.out);
        }
    }
}

class Task {
    final int N = 110;
    final int Inf = 1000000007;
    String S;
    int n;
    int B=0, aa=0;
    int m;
    int dp[][][][] = new int[N][235][52][2];
    int best=0;
    //Time Complexity must be O(N*N*M*2) ~ O(N*N*N)
    public int calc(int pos, int len, int remain, int s, PrintWriter out){
        if (remain<0) return -10000;
        if (pos==n && remain>0) return -10000000;
        if (pos==n && remain==0) return len;
        if (s==1){
            if (abs(len - (n-pos))<best) return 0;
        } else
        if (abs(len+(n - pos))<best) return 0;
        if (dp[pos][len+120][remain][s]>0) return dp[pos][len+120][remain][s];
        char c = S.charAt(pos);

        int p=0;
        if (c=='F'){
            if (s==1) p = max(p, calc(pos+1, len-1, remain, s ,out)); else
                p = max(p, calc(pos+1, len+1, remain, s, out));
        } else
        {
            p = max(p, calc(pos+1, len, remain, s, out));
        }
        if (remain>0) {
            if (c == 'F') {
                p = max(p, calc(pos + 1, len, remain - 1, s ^ 1, out));
            } else {
                if (s == 1) p = max(p, calc(pos + 1, len - 1, remain - 1, s ^ 1, out));
                else
                    p = max(p, calc(pos + 1, len + 1, remain - 1, s ^ 1, out));
            }
        }
        //out.println(pos+" "+len+" "+remain+" "+s+" = "+p);
        dp[pos][len+120][remain][s]=p;
        return p;
    }

    public void solve(int testNumber, FastScanner in, PrintWriter out) {
        S = in.next();
        best=0;
        int np=1;
        for (int i=0; i<S.length(); i++){
            char c = S.charAt(i);
            if (c=='T') {
                if (np==1) np=-1; else np = 1;
            } else best+=np;
        }
        n = S.length();
        m = in.nextInt();
        int ans = calc(0, 0, m, 0, out);
        ans = Math.max(ans, best);
        out.println(ans);

    }

}

class Pair implements Comparable<Pair>{
    public int first, second;
    Pair(){
        first=second=-1;
    }
    Pair(int a, int b){
        first = a; second=b;
    }
    @Override
    public int compareTo(Pair b){
        if (first<b.first) return 1; else
        if (first>b.first) return -1; else
        if (second<b.second)  return 1; else return -1;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        char c = (char)42;
        result = (int)(1L*first*second + first + second);
        if (second!=0) result+=first % second;
        if (first!=0) result+=second%first;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        Pair b = (Pair)obj;
        if (first==b.first && second==b.second) return true;
        return false;
    }

}

class PairComparator implements Comparator<Pair>{

    public int compare(Pair a, Pair b) {
        if (a.first<b.first) return 1; else
        if (a.first>b.first) return -1; else
        if (a.second<b.second)  return 1; else return -1;
    }
}

class FastScanner {
    BufferedReader br;
    StringTokenizer st;

    public FastScanner(File f) {
        try {
            br = new BufferedReader(new FileReader(f));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public FastScanner(InputStream f) {
        br = new BufferedReader(new InputStreamReader(f));
    }

    String next() {
        while (st == null || !st.hasMoreTokens()) {
            String s = null;
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (s == null)
                return null;
            st = new StringTokenizer(s);
        }
        return st.nextToken();
    }

    boolean hasMoreTokens() {
        while (st == null || !st.hasMoreTokens()) {
            String s = null;
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (s == null)
                return false;
            st = new StringTokenizer(s);
        }
        return true;
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class C {
    static int[][][] DP;
    static String s;
    static int[] M = { 1, -1 };
    static int inf = 10000000;

    public static int get(int index, int com, int m) {
        if (com < 0)
            return -inf;
        if (index == s.length())
            if (com == 0)
                return 0;
            else
                return -inf;
        if (DP[index][com][m] != -1)
            return DP[index][com][m];
        if (s.charAt(index) == 'F') {
            int max = -inf;
            for (int i = 0; i <= com; i++) {
                if (i % 2 == 0)
                    max = Math.max(max, M[m] + get(index + 1, com - i, m));
                else
                    max = Math.max(max, get(index + 1, com - 1, 1 - m));
            }
            return DP[index][com][m] = max;
        } else {
            int max = -inf;
            for (int i = 0; i <= com; i++) {
                if (i % 2 == 0)
                    max = Math.max(max, get(index + 1, com, 1 - m));
                else
                    max = Math.max(max, M[m] + get(index + 1, com - 1, m));
            }
            return DP[index][com][m] = max;
        }

    }

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        s = in.readLine();
        int n = Integer.parseInt(in.readLine());
        DP = new int[s.length()][n + 1][2];
        for (int i = 0; i < DP.length; i++)
            for (int j = 0; j < DP[0].length; j++)
                DP[i][j][0] = DP[i][j][1] = -1;
        System.out.println(get(0, n, 0));
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Artem Gilmudinov
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Reader in = new Reader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskE solver = new TaskE();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskE {
        public void solve(int testNumber, Reader in, PrintWriter out) {
            String s = in.rl();
            int n = s.length();
            int m = in.ni();
            int mid = 125;
            boolean[][][] dp = new boolean[250][m + 1][2]; //0-left, 1-right
            boolean[][][] prev = new boolean[250][m + 1][2];
            prev[mid][0][1] = true;
            int temp = 0;
            int dir = 0;
            for (int i = 0; i < n; i++) {
                for (int j = -101; j <= 101; j++) {
                    temp = j + mid;
                    for (int z = 0; z <= m; z++) {
                        for (int d = 0; d < 2; d++) {
                            if (d == 0) {
                                dir = 1;
                            } else {
                                dir = -1;
                            }
                            if (s.charAt(i) == 'F') {
                                for (int k = 0; k <= z; k++) {
                                    if (k % 2 == 0) {
                                        dp[temp][z][d] |= prev[temp + dir][z - k][d];
                                    } else {
                                        dp[temp][z][d] |= prev[temp][z - k][1 - d];
                                    }
                                }
                            } else {
                                for (int k = 0; k <= z; k++) {
                                    if (k % 2 == 0) {
                                        dp[temp][z][d] |= prev[temp][z - k][1 - d];
                                    } else {
                                        dp[temp][z][d] |= prev[temp + dir][z - k][d];
                                    }
                                }
                            }
                        }
                    }
                }
                for (int j = 0; j < 250; j++) {
                    for (int z = 0; z <= m; z++) {
                        for (int k = 0; k < 2; k++) {
                            prev[j][z][k] = dp[j][z][k];
                        }
                    }
                }
            }
            int ans = 0;
            for (int i = -101; i <= 101; i++) {
                for (int j = 0; j < 2; j++) {
                    if (dp[i + mid][m][j]) {
                        ans = Math.max(Math.abs(i), ans);
                    }
                }
            }
            out.println(ans);
        }

    }

    static class Reader {
        private BufferedReader in;
        private StringTokenizer st = new StringTokenizer("");
        private String delim = " ";

        public Reader(InputStream in) {
            this.in = new BufferedReader(new InputStreamReader(in));
        }

        public String next() {
            if (!st.hasMoreTokens()) {
                st = new StringTokenizer(rl());
            }
            return st.nextToken(delim);
        }

        public String rl() {
            try {
                return in.readLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        public int ni() {
            return Integer.parseInt(next());
        }

    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class LogoTurtle {
	static char[] arr;
	static Integer[][][][] dp = new Integer[102][50][102][2];
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
		String s=r.readLine();
		arr=s.toCharArray();
		int n=new Integer(r.readLine());
		System.out.println(solve(0,n,0,0));
	}
	// dir = 0 forward
	public static int solve(int index,int rem,int pos,int dir){
		if(rem<0)return -100000;
		if(pos<0)return -100000;
		if(index==arr.length)return pos;
		if(dp[index][rem][pos][dir]!=null)return dp[index][rem][pos][dir];
		if(arr[index]=='F'){
			int max=0;
			if(dir==0){
			max=solve(index+1,rem,pos+1,dir);
			max=Math.max(max, solve(index+1,rem-1,pos,1));
			}
			else{
				max=solve(index+1,rem,pos-1,1);
				max=Math.max(max, solve(index+1,rem-1,pos,0));
			}
			return dp[index][rem][pos][dir]=max;
		}
		else{
			int max=0;
			if(dir==0){
			max=solve(index+1,rem,pos,dir);
			max=Math.max(max, solve(index+1,rem-1,pos+1,1));
			}
			else{
				max=solve(index+1,rem,pos,1);
				max=Math.max(max, solve(index+1,rem-1,pos-1,0));
			}
			return dp[index][rem][pos][dir]=max;
		}

	}
}

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class realfast implements Runnable {
    private static final int INF = (int) 1e9;

    public  void solve() throws IOException
    {
      String s= readString();

      int n = readInt();

      int dp[][][][]= new int [s.length()+1][n+1][211][2];

      for(int i=0;i<s.length();i++)
        for(int j=0;j<=n;j++)
            for(int k=0;k<=210;k++)
                for(int l=0;l<=1;l++)
                    dp[i][j][k][l]=-1;

      int val = dp(dp,0,0,n,s,0);

      out.println(val);

    }
    public  int dp(int dp[][][][], int i, int dist, int n,String s, int check)
    {
        if(i==s.length())
        {
           if(n==0)
           {
             return Math.abs(dist);
           }
           else
            return 0;
        }

        if(dp[i][n][100+dist][check]!=-1){

            return dp[i][n][100+dist][check];
        }

        if(s.charAt(i)=='T')
        {
            if(check==0)
            {
                for(int k=n;k>=0;k=k-2)
             dp[i][n][dist+100][check]=Math.max(dp[i][n][dist+100][check],dp(dp,i+1,dist,k,s,(check+1)%2));
             if(n>0)
             {
              for(int k=n;k>=1;k=k-2)
             dp[i][n][dist+100][check] =Math.max( dp(dp,i+1,dist+1,k-1,s,check),dp[i][n][100+dist][check]);
             }
            }
            else
            {
              for(int k=n;k>=0;k=k-2)
             dp[i][n][dist+100][check]=Math.max(dp[i][n][dist+100][check],dp(dp,i+1,dist,k,s,(check+1)%2));
             if(n>0)
             {
               for(int k=n;k>=1;k=k-2)
              dp[i][n][dist+100][check]= Math.max(dp(dp,i+1,dist-1,k-1,s,check),dp[i][n][dist+100][check]);
             }
            }
        }
        else
        {
            if(check==0){
                for(int k=n;k>=0;k=k-2)
                dp[i][n][dist+100][check]=Math.max(dp[i][n][dist+100][check],dp(dp,i+1,dist+1,k,s,0));
                if(n>0){
                for(int k=n;k>=1;k=k-2)
                dp[i][n][dist+100][check]=Math.max(dp[i][n][dist+100][check],dp(dp,i+1,dist,k-1,s,1));
                }
            }
            else
            {
                for(int k=n;k>=0;k=k-2)
                dp[i][n][dist+100][check]=dp(dp,i+1,dist-1,k,s,1);
                if(n>0){
                    for(int k=n;k>=1;k=k-2)
                    dp[i][n][dist+100][check]=Math.max(dp[i][n][dist+100][check],dp(dp,i+1,dist,k-1,s,0));
                }
            }
        }
        return dp[i][n][dist+100][check];
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static void main(String[] args) {
        new Thread(null, new realfast(), "", 128 * (1L << 20)).start();
    }

    private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
    private BufferedReader reader;
    private StringTokenizer tokenizer;
    private PrintWriter out;

    @Override
    public void run() {
        try {
            if (ONLINE_JUDGE || !new File("input.txt").exists()) {
                reader = new BufferedReader(new InputStreamReader(System.in));
                out = new PrintWriter(System.out);
            } else {
                reader = new BufferedReader(new FileReader("input.txt"));
                out = new PrintWriter("output.txt");
            }
            solve();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                // nothing
            }
            out.close();
        }
    }

    private String readString() throws IOException {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            tokenizer = new StringTokenizer(reader.readLine());
        }
        return tokenizer.nextToken();
    }

    @SuppressWarnings("unused")
    private int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    @SuppressWarnings("unused")
    private long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    @SuppressWarnings("unused")
    private double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }
}
class edge implements Comparable<edge>{
    int u ;
    int v ;
    int val;
    edge(int u1, int v1 , int val1)
    {
       this.u=u1;
       this.v=v1;
       this.val=val1;
    }
    public int compareTo(edge e)
    {
        return this.val-e.val;
    }
}

import java.util.*;

public class Main {

  public static void main(String args[]) {
    (new Main()).solve();
  }

  void solve() {

    Scanner cin = new Scanner(System.in);

    while( cin.hasNext() ) {

      String s = cin.next();
      int k = cin.nextInt();
      int n = s.length();

      int inf = 10000;

      int dp[][][] = new int[n+1][k+1][2];
      for(int i=0; i<=n; ++i) {
        for(int j=0; j<=k; ++j) {
          dp[i][j][0] = -inf;
          dp[i][j][1] = inf;
        }
      }
      dp[0][0][0] = dp[0][0][1] = 0;

      int Tsum = 0;

      for(int i=0; i<n; ++i) {
        int curT = s.charAt(i) == 'T' ? 1 : 0;
        int curF = 1 - curT;
        Tsum += curT;
        for(int j=0; j<=k; ++j) {
          if( dp[i][j][0] == inf ) { continue; }
          for(int use=0; use<=curT; ++use) {
            if( j + use > k ) { break; }
            int dir = ((Tsum - (j + use)) % 2) == 1 ? -1 : 1;
            dp[i+1][j+use][0] = Math.max(dp[i+1][j+use][0], dp[i][j][0] + (curF + use) * dir);
            dp[i+1][j+use][1] = Math.min(dp[i+1][j+use][1], dp[i][j][1] + (curF + use) * dir);
          }
        }
      }

      int ret = Math.max(Math.abs(dp[n][k][0]), Math.abs(dp[n][k][1]));
      if( ret == inf ) {
        ret = n - (k - Tsum) % 2;
      }
      System.out.println(ret);

    }

  }

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class R96D2_E {
    static String inp;
    static int n;
    static int st;
    static int DP[][][];

    public static int call(int i, int rem, int add) {
        if (i == n && rem == 0)
            return 0;
        if (i == n || rem<0)
            return -1000000;
        int d = add == -1 ? 1 : 0;

        if (DP[i][rem][d] != -1)
            return DP[i][rem][d];

        if (rem == 0) {
            if (inp.charAt(i) == 'F')
                return DP[i][rem][d] = add + call(i + 1, rem, add);
            else
                return DP[i][rem][d] = call(i + 1, rem, add * -1);
        } else {
            int res = 0;
            int res2 = 1;
            for (int j = 0; j <= rem; j++) {
                if ((inp.charAt(i) == 'F' && j % 2 == 0)
                        || (inp.charAt(i) == 'T' && j % 2 == 1)){
                    int y = add + call(i + 1, rem - j,  add);
                    if(y<10000 && y>-10000){
                    res = Math.max(res, Math.abs(y));
                    if(y<0)
                    res2 = -1;
                    }else
                        res2 = 1;
                }else{
                    int y = call(i + 1, rem - j, -1 * add);
                    if(y<10000 && y>-10000){
                    res = Math.max(res, Math.abs(y));
                    if(y<0)
                        res2 = -1;
                    }else
                        res2 = 1;
                }
            }
            return DP[i][rem][d] = res*res2;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        // int n = Integer.parseInt(in.readLine());
        // String []s = in.readLine().split(" ");
        inp = in.readLine();
        n = inp.length();
        st = Integer.parseInt(in.readLine());
        DP = new int[n][st + 1][2];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < st + 1; j++) {
                for (int k = 0; k < 2; k++) {
                    DP[i][j][k] = -1;
                }
            }

        }
        System.out.println(Math.abs(call(0,st,1)));
    }
}

import java.util.*;

public class Main {

  public static void main(String args[]) {
    (new Main()).solve();
  }

  void solve() {

    Scanner cin = new Scanner(System.in);

    while( cin.hasNext() ) {

      String s = cin.next();
      int k = cin.nextInt();
      int n = s.length();

      ArrayList<Integer> T = new ArrayList<Integer>();
      ArrayList<Integer> F = new ArrayList<Integer>();

      int t = 0;
      int f = 0;

      for(int i=0; i<=n; ++i) {
        if( i == n || s.charAt(i) == 'T' ) {
          if( f > 0 ) {
            T.add(t);
            F.add(f);
            t = f = 0;
          }
          ++t;
        }
        else {
          ++f;
        }
      }

      // tail;
      if( t > 1 ) {
        T.add(t - 1);
        F.add(f);
      }

      int g = F.size();

      int inf = 10000;

      int dp[][][] = new int[g+1][k+1][2];
      for(int i=0; i<=g; ++i) {
        for(int j=0; j<=k; ++j) {
          dp[i][j][0] = -inf;
          dp[i][j][1] = inf;
        }
      }
      dp[0][0][0] = dp[0][0][1] = 0;

      int Tsum = 0;

      for(int i=0; i<g; ++i) {
        int curT = T.get(i);
        int curF = F.get(i);
        Tsum += curT;
        for(int j=0; j<=k; ++j) {
          if( dp[i][j][0] == inf ) { continue; }
          for(int use=0; use<=curT; ++use) {
            if( j + use > k ) { break; }
            int dir = ((Tsum - (j + use)) % 2) == 1 ? -1 : 1;
            dp[i+1][j+use][0] = Math.max(dp[i+1][j+use][0], dp[i][j][0] + (curF + use) * dir);
            dp[i+1][j+use][1] = Math.min(dp[i+1][j+use][1], dp[i][j][1] + (curF + use) * dir);
          }
        }
      }

      int ret = Math.max(Math.abs(dp[g][k][0]), Math.abs(dp[g][k][1]));
      if( ret == inf ) {
        ret = n - (k - Tsum) % 2;
      }
      System.out.println(ret);

    }

  }

}

import java.util.Scanner;

public class C {

    void run(){
        Scanner sc = new Scanner(System.in);
        char[] s = sc.next().toCharArray();
        int K = sc.nextInt();
        int n = s.length;
        int INF = -(1<<29);
        int[][][] dp = new int[n][K+1][2];
        for(int i=0;i<n;i++)for(int j=0;j<=K;j++)for(int k=0;k<2;k++)dp[i][j][k]=INF;
        if(s[n-1]=='F'){
            dp[n-1][1][0] = 0;
            dp[n-1][1][1] = 0;
            dp[n-1][0][0] = -1;
            dp[n-1][0][1] = 1;
        }
        else{
            dp[n-1][1][0] = -1;
            dp[n-1][1][1] = 1;
            dp[n-1][0][0] = 0;
            dp[n-1][0][1] = 0;
        }
        for(int i=n-2;i>=0;i--)for(int k=0;k<=K;k++){
            boolean F = s[i]=='F';
            if(F){
                int max = INF;
                max = Math.max(max, -1+dp[i+1][k][0]);
                if(k>0)max = Math.max(max, dp[i+1][k-1][1]);
                dp[i][k][0] = max;
                max = INF;
                max = Math.max(max, 1+dp[i+1][k][1]);
                if(k>0)max = Math.max(max, dp[i+1][k-1][0]);
                dp[i][k][1] = max;
            }
            else{
                int max = INF;
                max = Math.max(max, dp[i+1][k][1]);
                if(k>0)max = Math.max(max, -1+dp[i+1][k-1][0]);
                dp[i][k][0] = max;
                max = INF;
                max = Math.max(max, dp[i+1][k][0]);
                if(k>0)max = Math.max(max, 1+dp[i+1][k-1][1]);
                dp[i][k][1] = max;
            }
        }
        System.out.println(dp[0][K][1]);
    }

    public static void main(String[] args) {
        new C().run();
    }
}

import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Fantast
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		Scanner in = new Scanner(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskE solver = new TaskE();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskE {
    int n;
    char[] s;
    public void solve(int testNumber, Scanner in, PrintWriter out) {
        s = in.next().toCharArray();
        n = in.nextInt();

        for (int i = 0; i < 101; ++i) {
            for (int j = 0; j < 2; ++j) {
                for (int k = 0; k < 101; ++k) {
                    mxs[i][j][k] = -1;
                    mns[i][j][k] = -1;
                }
            }
        }

        out.println(
                mx(
                        Math.abs(mxdist(0, 1, n)),
                        Math.abs(mndist(0, 1, n)),
                        Math.abs(mxdist(0, -1, n)),
                        Math.abs(mndist(0, -1, n))
                ));
    }

    private int mx(int... a) {
        int res = a[0];
        for (int n : a) {
            res = Math.max(res, n);
        }
        return res;
    }

    int mxs[][][] = new int[101][2][101];
    public int mxdist(int ind, int dir, int tochange) {
        if (tochange > s.length - ind || tochange < 0) {
            return Integer.MIN_VALUE / 2;
        }

        if (ind == s.length) {
            return 0;
        }

        int di = (dir+1)/2;
        if (mxs[ind][di][tochange] != -1) {
            return mxs[ind][di][tochange];
        }

        int res;
        if (s[ind] == 'T') {
            res = Math.max(
                    mxdist(ind + 1, -dir, tochange),
                    dir + mxdist(ind + 1, dir, tochange - 1));
        } else {
            res = Math.max(
                    dir + mxdist(ind + 1, dir, tochange),
                    mxdist(ind + 1, -dir, tochange - 1));
        }

        return mxs[ind][di][tochange] = res;
    }

    int mns[][][] = new int[101][2][101];
    public int mndist(int ind, int dir, int tochange) {
        if (tochange > s.length - ind || tochange < 0) {
            return Integer.MAX_VALUE / 2;
        }

        if (ind == s.length) {
            return 0;
        }

        int di = (dir+1)/2;
        if (mns[ind][di][tochange] != -1) {
            return mns[ind][di][tochange];
        }

        int res;
        if (s[ind] == 'T') {
            res = Math.min(
                    mndist(ind + 1, -dir, tochange),
                    dir + mndist(ind + 1, dir, tochange - 1));
        } else {
            res = Math.min(
                    dir + mndist(ind + 1, dir, tochange),
                    mndist(ind + 1, -dir, tochange - 1));
        }

        return mns[ind][di][tochange] = res;
    }
}

import java.util.Scanner;

public class LogoTurtle {
	int [][][] dp;
	boolean [][][] visited;
	String s;

	public LogoTurtle(int[][][] dp, boolean[][][] visited, String s) {
		super();
		this.dp = dp;
		this.visited = visited;
		this.s = s;
	}
	int score(String s,boolean f,boolean c) {
		int ans = 0;
		if((s.charAt(0) == 'F' && c)||(s.charAt(0) == 'T') && !c) {
			if(f) {
				ans ++ ;
			}else {
				ans -- ;
			}
		}else {
			f=!f;
		}
		for (int i = 1; i < s.length(); i++) {
			if(s.charAt(i) == 'F') {
				if(f) {
					ans ++ ;
				}else {
					ans -- ;
				}
			}else {
				f=!f;
			}
		}
		return Math.abs(ans);
	}
	int solve(int idx,int rem,int score, boolean f) {
		if(idx == s.length() -1 && rem != 0) {
			if(rem%2 ==0 ) {
				return score + score(s.substring(idx, s.length()),f, true);
			}else {
				return score + score(s.substring(idx, s.length()),f, false);
			}
		}
		if(idx == s.length() && rem == 0) {
			return score;
		}
		if (rem < 0) {
			return Integer.MIN_VALUE;
		}
		if (visited[idx][rem][score + 100] ) {
			return dp[idx][rem][score + 100];
		}
		visited[idx][rem][score + 100] = true;
		if(rem == 0) {

			dp[idx][rem][score + 100] =score + score(s.substring(idx, s.length()),f,true) ;
			return dp[idx][rem][score +100];
		}

		int z,y;
		if(s.charAt(idx) == 'T' ) {

			 y = solve(idx + 1, rem -1 , f?score +1 : score - 1, f);
		}else {

			 y = solve(idx + 1, rem -1, score, !f);
		}
		if(s.charAt(idx) == 'F' ) {

			 z = solve(idx + 1, rem , f?score +1 : score - 1, f);
		}else {

			 z = solve(idx + 1, rem , score, !f);
		}
		dp[idx][rem][score + 100] = Math.abs(y)> Math.abs(z)?y:z ;
		return dp[idx][rem][score + 100];
	}
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String s = in.nextLine();
		int n = in.nextInt();
		LogoTurtle x = new LogoTurtle(new int [s.length()][n + 1][201], new boolean [s.length()][n + 1][201],s);
		System.out.println(Math.abs(x.solve(0, n, 0, true)));
	}

}

import java.io.*;
import java.util.*;

public class C {

	public C () throws IOException {
		char [] commands = sc.next().toCharArray();
		int N = sc.nextInt();
		solve(commands, N);
	}

	public void solve (char [] C, int N) {

		int L = C.length;
		while (N > 0) {
			// 1. All Fs
			String cmd = new String(C);
			if (cmd.indexOf('T') == -1) {
				C[0] = 'T';
				--N;
			}

			// 2. N == 1
			else if (N == 1) {
				int S = -1;
				for (int i = 0; i < L; ++i) {
					C[i] = ch(C[i]);
					S = Math.max(S, eval(C));
					C[i] = ch(C[i]);
				}
				print(S);
			}

			else {
				int count = 0;
				for (int i = 0; i < L; ++i) {
					if (C[i] == 'T')
						++count;
				}

				// 3. N >= 2, just one T
				if (count == 1) {
					for (int i = 0; i < L; ++i) {
						if (C[i] == 'T')
							C[i] = 'F';
					}
					--N;
				} else {
					int S = 0, x = -1, y = -1, z = -1;
					for (int i = 0; i < L; ++i) {
						for (int j = i+1; j < L; ++j)
							if (C[i] == 'T' && C[j] == 'T') {
								C[i] = ch(C[i]); C[j] = ch(C[j]);
								int E = eval(C);
								if (E >= S) {
									S = E; x = i; y = j;
								}
								C[i] = ch(C[i]); C[j] = ch(C[j]);
						}
						if (C[i] == 'T') {
							C[i] = ch(C[i]);
							int E = eval(C);
							if (E > S) {
								S = E; z = i;
							}
							C[i] = ch(C[i]);
						}
					}
					if (z >= 0) {
						C[z] = 'F'; --N;
					} else {
						C[x] = C[y] = 'F'; N -= 2;
					}
				}
			}
		}

		print (eval(C));
	}

	int eval (char [] C) {
		int x = 0, d = 1;
		for (char c : C) {
			if (c == 'T')
				d = -d;
			if (c == 'F')
				x += d;
		}
		return Math.abs(x);
	}

	char ch (char X) {
		if (X == 'F') return 'T';
		else return 'F';
	}

	////////////////////////////////////////////////////////////////////////////////////

	static Scanner sc;
	static long t;

	static void print2 (Object o) {
		System.out.println(o);
	}

	static void print (Object o) {
		print2(o);
		//print2((millis() - t) / 1000.0);
		System.exit(0);
	}

	static void run () throws IOException {
		sc = new Scanner(System.in);
		new C();
	}

	public static void main(String[] args) throws IOException {
		run();
	}

	static long millis() {
		return System.currentTimeMillis();
	}
}

import java.util.Scanner;

public class CF133E {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String commands = sc.next();
        int n = sc.nextInt();

        State[][][] dp = new State[commands.length()+1][n+1][4];
        State init = State.valueOf(0, 0, Direction.LEFT);
        dp[0][0][0] = init;
        for (int i = 1; i < dp.length; i++) {
            boolean commandIsT = commands.charAt(i-1) == 'T';
            for (int j = 0; j < 4; j++) {
                if(dp[i-1][0][(commandIsT ? j+1 : j) % 4] != null) {
                    dp[i][0][j] = dp[i-1][0][(commandIsT ? j+1 : j) % 4].command(commandIsT);
                }
            }
            for (int j = 1; j < n+1; j++) {
                for (int k = 0; k < 4; k++) {
                    State fromLeft = null;
                    State fromTopLeft = null;
                    State fromTop = j > 1 ? dp[i][j-2][k] : null;
                    if (commandIsT) {
                        if(dp[i-1][j][(k-1+4)%4] != null) fromLeft = dp[i-1][j][(k-1+4)%4].turnAround();
                        if(dp[i-1][j-1][k] != null) fromTopLeft = dp[i-1][j-1][k].forward();
                    }
                    else {
                        if(dp[i-1][j][k] != null) fromLeft = dp[i-1][j][k].forward();
                        if(dp[i-1][j-1][(k-1+4)%4] != null) fromTopLeft = dp[i-1][j-1][(k-1+4)%4].turnAround();
                    }
                    dp[i][j][k] = State.getBigger(fromLeft, State.getBigger(fromTopLeft, fromTop));
                }
            }
        }
        int max = 0;
        for (int i = 0; i < 4; i++) {
            if(dp[commands.length()][n][i] != null)
                max = Math.max(max, dp[commands.length()][n][i].dist);
        }
        System.out.println((int)Math.sqrt(max));
    }

    enum Direction {
        LEFT(-1,0), UP(0,-1), RIGHT(1,0), DOWN(0,1);

        private Direction(int x, int y) {
            dx = x;
            dy = y;
        }
        int dx,dy;
    }

    static class State {
        final int x;
        final int y;
        final Direction dir;
        final int dist;
        public State(int x, int y, Direction dir) {
            this.x = x;
            this.y = y;
            this.dir = dir;
            dist = x*x+y*y;
        }
        static State valueOf(int x, int y, Direction dir) {
            return new State(x, y, dir);
        }
        State forward() {
            return valueOf(x + dir.dx, y + dir.dy, dir);
        }
        State turnAround() {
            if (valuesTemp == null) {
                valuesTemp = Direction.values();
            }
            return valueOf(x, y, valuesTemp[(dir.ordinal() + 1) % valuesTemp.length]);
        }
        static Direction[] valuesTemp;
        State command(boolean c) {
            return c ? turnAround() : forward();
        }

        static State getBigger(State a, State b) {
            if (a == null) return b;
            if (b == null) return a;
            return a.dist > b.dist ? a : b;
        }

    }

}

import java.io.Closeable;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.AbstractList;
import java.io.Writer;
import java.util.Collection;
import java.util.List;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Jacob Jiang
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		QuickScanner in = new QuickScanner(inputStream);
		ExtendedPrintWriter out = new ExtendedPrintWriter(outputStream);
		TaskC solver = new TaskC();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskC {
    public static final int INF = Integer.MAX_VALUE / 20;

	public void solve(int testNumber, QuickScanner in, ExtendedPrintWriter out) {
        char[] commands = (" " + in.next()).toCharArray();
        int n = commands.length - 1;
        int toChange = in.nextInt();
        int[][][] minPosition = new int[n + 1][toChange + 1][2];
        int[][][] maxPosition = new int[n + 1][toChange + 1][2];
        ArrayUtils.fill(minPosition, INF);
        ArrayUtils.fill(maxPosition, -INF);
        Arrays.fill(minPosition[0][0], 0);
        Arrays.fill(maxPosition[0][0], 0);
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= toChange; j++) {
                for (int k = 0; k < 2; k++) {
                    //not change
                    if (commands[i] == 'T') {
                        minPosition[i][j][k] = Math.min(minPosition[i][j][k], minPosition[i - 1][j][1 - k]);
                        maxPosition[i][j][k] = Math.max(maxPosition[i][j][k], maxPosition[i - 1][j][1 - k]);
                    } else {
                        minPosition[i][j][k] = Math.min(minPosition[i][j][k], minPosition[i - 1][j][k] + toward(k));
                        maxPosition[i][j][k] = Math.max(maxPosition[i][j][k], maxPosition[i - 1][j][k] + toward(k));
                    }
                    //change
                    if (j > 0) {
                        if (commands[i] == 'T') {
                            minPosition[i][j][k] = Math.min(minPosition[i][j][k], minPosition[i - 1][j - 1][k] + toward(k));
                            maxPosition[i][j][k] = Math.max(maxPosition[i][j][k], maxPosition[i - 1][j - 1][k] + toward(k));
                        } else {
                            minPosition[i][j][k] = Math.min(minPosition[i][j][k], minPosition[i - 1][j - 1][1 - k]);
                            maxPosition[i][j][k] = Math.max(maxPosition[i][j][k], maxPosition[i - 1][j - 1][1 - k]);
                        }
                    }
                }
            }
        }
        int answer = 0;
        for (int k = 0; k < 2; k++) {
            answer = Math.max(answer, -minPosition[n][toChange][k]);
            answer = Math.max(answer, maxPosition[n][toChange][k]);
        }
        out.println(answer);

    }

    private int toward(int x) {
        return x == 0 ? 1 : -1;
    }
}

class QuickScanner implements Iterator<String>, Closeable {
    BufferedReader reader;
    StringTokenizer tokenizer;
    boolean endOfFile = false;

    public QuickScanner(InputStream inputStream) {
        reader = new BufferedReader(new InputStreamReader(inputStream));
        tokenizer = null;
    }

    public boolean hasNext() {
        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                checkNext();
            } catch (NoSuchElementException ignored) {
            }

        }
        return !endOfFile;
    }

    private void checkNext() {
        if (endOfFile) {
            throw new NoSuchElementException();
        }
        try {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                tokenizer = new StringTokenizer(reader.readLine());
            }
        } catch (Exception e) {
            endOfFile = true;
            throw new NoSuchElementException();
        }
    }

    public String next() {
        checkNext();
        return tokenizer.nextToken();
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }

    public int nextInt() {
        return Integer.parseInt(next());
    }

    public void close() {
        try {
            reader.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

class ExtendedPrintWriter extends PrintWriter {

    public ExtendedPrintWriter(Writer out) {
        super(out);
    }

    public ExtendedPrintWriter(OutputStream out) {
        super(out);
    }

    }

class ArrayUtils {

    private ArrayUtils() {
    }

    public static void fill(int[][] array, int val) {
        for (int[] subArray : array) {
            Arrays.fill(subArray, val);
        }
    }

    public static void fill(int[][][] array, int val) {
        for (int[][] subArray : array) {
            ArrayUtils.fill(subArray, val);
        }
    }

    }

import java.io.*;
import java.util.*;

public class C {

	public C () throws IOException {
		char [] commands = sc.next().toCharArray();
		int N = sc.nextInt();
		print(solve(commands, N));
	}

	public int solve (char [] C, int N) {

		int L = C.length;
		while (N > 0) {
			// 1. All Fs
			String cmd = new String(C);
			if (cmd.indexOf('T') == -1) {
				C[0] = 'T';
				--N;
			}

			// 2. N == 1
			else if (N == 1) {
				int S = -1;
				for (int i = 0; i < L; ++i) {
					C[i] = ch(C[i]);
					S = Math.max(S, eval(C));
					C[i] = ch(C[i]);
				}
				return S;
			}

			else {
				int count = 0;
				for (int i = 0; i < L; ++i) {
					if (C[i] == 'T')
						++count;
				}

				// 3. N >= 2, just one T
				if (count == 1) {
					for (int i = 0; i < L; ++i) {
						if (C[i] == 'T')
							C[i] = 'F';
					}
					--N;
				} else {
					int S = 0, x = -1, y = -1, z = -1;
					for (int i = 0; i < L; ++i) {
						// Look for the best pair to change - prefer farther ones!
						for (int j = i+1; j < L; ++j)
							if (C[i] == 'T' && C[j] == 'T') {
								C[i] = ch(C[i]); C[j] = ch(C[j]);
								int E = eval(C);
								if (E >= S) {
									S = E; x = i; y = j;
								}
								C[i] = ch(C[i]); C[j] = ch(C[j]);
						}
						// Look for best single to change - prefer farther ones!
						if (C[i] == 'T') {
							C[i] = ch(C[i]);
							int E = eval(C);
							if (E >= S) {
								S = E; z = i;
							}
							C[i] = ch(C[i]);
						}
					}

					if (z >= 0) {
						char [] D = new char[L];
						for (int i = 0; i < L; ++i)
							D[i] = C[i];
						C[x] = C[y] = D[z] = 'F';
						return Math.max(solve(C, N-2), solve(D, N-1));
					} else
						return solve(C, N-2);
				}
			}
		}

		return eval(C);
	}

	int eval (char [] C) {
		int x = 0, d = 1;
		for (char c : C) {
			if (c == 'T')
				d = -d;
			if (c == 'F')
				x += d;
		}
		return Math.abs(x);
	}

	char ch (char X) {
		if (X == 'F') return 'T';
		else return 'F';
	}

	////////////////////////////////////////////////////////////////////////////////////

	static Scanner sc;
	static long t;

	static void print2 (Object o) {
		System.out.println(o);
	}

	static void print (Object o) {
		print2(o);
		//print2((millis() - t) / 1000.0);
		System.exit(0);
	}

	static void run () throws IOException {
		sc = new Scanner(System.in);
		new C();
	}

	public static void main(String[] args) throws IOException {
		run();
	}

	static long millis() {
		return System.currentTimeMillis();
	}
}

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String s = in.next();
		int n = in.nextInt();
		int t;
		char[] tmp;
		int max = -1;
		int r;
		for (int i = 0; i < s.length(); i++) {
			tmp = s.toCharArray();
			t = n;
			for (int j = i; j < s.length(); j++) {
				if (tmp[j] == 'T') {
					t--;
					tmp[j] = 'F';
				}
				if (t == 0)
					break;
			}
			r = getMax(tmp);
			if (t != 0) {
				if (r == tmp.length) {
					if (t % 2 != 0)
						r--;
				}
			}
			max = Math.max(max, r);
		}
		System.out.println(max);
	}

	public static int getMax(char[] a) {
		int cnt = 0;
		boolean f = true;
		for (int i = 0; i < a.length; i++) {
			if (a[i] == 'F') {
				if (f)
					cnt++;
				else
					cnt--;
			} else {
				f = !f;
			}
		}
		return Math.abs(cnt);
	}
}

import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class Main{
	public static void main(String[]args){
		InputStream in = System.in;
		PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
		try{
//			in = new BufferedInputStream(new FileInputStream(new File("input.txt")));
//			out = new PrintWriter(new BufferedOutputStream(new FileOutputStream("output.txt")));
		}catch (Exception e) {
		}
		new Main().run(in,out);
		out.flush();
	}
	private void debug(Object...os){
		System.err.println(deepToString(os));
	}

	private void run(InputStream in,PrintWriter out){
		char[]cs = next(in).toCharArray();
		int m=nextInt(in);
		int n=cs.length;
		int off = n+5;
		boolean[][][] dp=new boolean[2][n*2+10][m+1];// step,dist,used
		dp[0][off][0]=true;
		int cur=0,nxt=1;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n*2+10; j++) {
				fill(dp[nxt][j],false);
			}
			for (int j = 0; j < n*2+10; j++) {
				for (int k = 0; k < m; k++) {
					if(dp[cur][j][k]){
//						debug(i,j,k);
						// change
						boolean turn = cs[i]=='F';
						int add = 1;
						if(k+add<=m)dp[nxt][turn?off-(j-off) : j+1][k+add] = true;
						// as is
						turn = cs[i]=='T';
						add=0;
						if(k+add<=m)dp[nxt][turn?off-(j-off) : j+1][k+add] = true;
					}
				}
			}
			int tmp=cur;cur=nxt;nxt=tmp;
		}
		int res = 0;
		for (int i = 0; i < n*2+10; i++) {
			if(dp[cur][i][m])res = max(res,abs(off-i));
		}
		out.println(res);
	}

    private String next(InputStream in) {
        try {
            StringBuilder res = new StringBuilder("");
            int c = in.read();
            while (Character.isWhitespace(c))
                c = in.read();
            do {
                res.append((char) c);
            } while (!Character.isWhitespace(c = in.read()));
            return res.toString();
        } catch (Exception e) {
            return null;
        }
    }

	private int nextInt(InputStream in){
		try{
			int c=in.read();
			if(c==-1) return c;
			while(c!='-'&&(c<'0'||'9'<c)){
				c=in.read();
				if(c==-1) return c;
			}
			if(c=='-') return -nextInt(in);
			int res=0;
			do{
				res*=10;
				res+=c-'0';
				c=in.read();
			}while('0'<=c&&c<='9');
			return res;
		}catch(Exception e){
			return -1;
		}
	}

	private long nextLong(InputStream in){
		try{
			int c=in.read();
			if(c==-1) return c;
			while(c!='-'&&(c<'0'||'9'<c)){
				c=in.read();
				if(c==-1) return c;
			}
			if(c=='-') return -nextLong(in);
			long res=0;
			do{
				res*=10;
				res+=c-'0';
				c=in.read();
			}while('0'<=c&&c<='9');
			return res;
		}catch(Exception e){
			return -1;
		}
	}
}

import javax.sound.sampled.Line;
import java.awt.Point;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.math.BigInteger.*;

import java.math.MathContext;
import java.util.*;
public class C{

    void solve()throws Exception
    {
       char[]s=nextString().toCharArray();
       int changes=nextInt();
       boolean[][][][]dp=new boolean[2][s.length+1][s.length+1][changes+1];//dir,atCommand,at,changes
        dp[0][0][0][0]=true;
        dp[1][0][0][0]=true;

        for(int ch=0;ch<=changes;ch++)
            for(int at=0;at<s.length;at++)
                for(int atPoint=0;atPoint<=s.length;atPoint++)
                    for(int dir=0;dir<=1;dir++)
                        if(dp[dir][at][atPoint][ch])
                        {
                            char c=s[at];
                            for(int curChange=0;curChange+ch<=changes;curChange++)
                            {
                                int x=curChange%2;
                                int nch=ch+curChange;
                                int ndir=dir;
                                char curCommand;
                                if(x==0)
                                    curCommand=c;
                                else
                                    curCommand=(char)('F'+'T'-c);
                                if(curCommand=='T')
                                    ndir=1-dir;
                                int nPoint=atPoint;
                                if(curCommand=='F')
                                {
                                    if(ndir==0)
                                        nPoint++;
                                    else
                                        nPoint--;
                                }
                                if(nPoint<0)
                                {
                                    nPoint=-nPoint;
                                    ndir=1-ndir;
                                }
                                dp[ndir][at+1][nPoint][nch]=true;

                            }
                        }
      int res=0;
      for(int atPoint=0;atPoint<=s.length;atPoint++)
          if(dp[0][s.length][atPoint][changes])
              res=atPoint;
        System.out.println(res);
    }

    ////////////
    BufferedReader reader;
    PrintWriter writer;
    StringTokenizer stk;
    void run()throws Exception
    {
        reader=new BufferedReader(new InputStreamReader(System.in));
        stk=null;
        writer=new PrintWriter(new PrintWriter(System.out));
        solve();
        reader.close();
        writer.close();
    }
    int nextInt()throws Exception
    {
        return Integer.parseInt(nextToken());
    }

    long nextLong()throws Exception
    {
        return Long.parseLong(nextToken());

    }
    double nextDouble()throws Exception
    {
        return Double.parseDouble(nextToken());

    }

    String nextString()throws Exception
    {
        return nextToken();
    }
    String nextLine()throws Exception
    {
        return reader.readLine();
    }
    String nextToken()throws Exception
    {
        if(stk==null || !stk.hasMoreTokens())
        {
            stk=new StringTokenizer(nextLine());
            return nextToken();

        }
        return stk.nextToken();
    }

    public static void main(String[]args) throws Exception
    {
        new C().run();
    }

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class R96D2_E {
    static String inp;
    static int n;
    static int st;
    static int DP[][][];

    public static int call(int i, int rem, int add) {
        if (i == n && rem == 0)
            return 0;
        if (i == n || rem<0)
            return -1000000;
        int d = add == -1 ? 1 : 0;

        if (DP[i][rem][d] != -1)
            return DP[i][rem][d];

        if (rem == 0) {
            if (inp.charAt(i) == 'F')
                return DP[i][rem][d] = add + call(i + 1, rem, add);
            else
                return DP[i][rem][d] = call(i + 1, rem, add * -1);
        } else {
            int res = 0;
            int res2 = 1;
            for (int j = 0; j <= rem; j++) {
                if ((inp.charAt(i) == 'F' && j % 2 == 0)
                        || (inp.charAt(i) == 'T' && j % 2 == 1)){
                    int y = add + call(i + 1, rem - j,  add);
                    if(y<10000 && y>-10000){
                    res = Math.max(res, Math.abs(y));
                    if(y<0)
                    res2 = -1;
                    else
                        res2 = 1;
                    }
                }else{
                    int y = call(i + 1, rem - j, -1 * add);
                    if(y<10000 && y>-10000){
                    res = Math.max(res, Math.abs(y));
                    if(y<0)
                        res2 = -1;
                    else
                        res2 = 1;
                    }
                }
            }
            return DP[i][rem][d] = res*res2;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        // int n = Integer.parseInt(in.readLine());
        // String []s = in.readLine().split(" ");
        inp = in.readLine();
        n = inp.length();
        st = Integer.parseInt(in.readLine());
        DP = new int[n][st + 1][2];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < st + 1; j++) {
                for (int k = 0; k < 2; k++) {
                    DP[i][j][k] = -1;
                }
            }

        }
        System.out.println(Math.abs(call(0,st,1)));
    }
}

import java.util.Arrays;
import java.util.Scanner;
import static java.lang.Math.*;

public class turtle {
    public static void debug(Object... obs) {
        System.out.println(Arrays.deepToString(obs));
    }

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);

        String s=sc.next();
        int k=sc.nextInt();
        int n=s.length();

        int[][][][]dp=new int[n+1][k+1][2][2];
        boolean[][][]reach=new boolean[n+1][k+1][2];
        final int[]sg={1,-1};

        for(int i=0;i<=n;i++)
        {
            for(int j=0;j<=k;j++)
            {
                for(int l=0;l<sg.length;l++)
                {
                    dp[i][j][l][0]=Integer.MIN_VALUE;
                    dp[i][j][l][1]=Integer.MAX_VALUE;
                }
            }
        }
        dp[0][0][0][0]=0;
        dp[0][0][0][1]=0;
        reach[0][0][0]=true;

        for(int i=1;i<=n;i++)
        {
            int trn=0;
            int inc=1;
            if(s.charAt(i-1)=='T')
            {
                trn=1;
            }
            for(int j=0;j<=k;j++)
            {
                for(int f=0;f<=j;f++)
                {
                    int d=(j-f+trn)%2;
                    for(int l=0;l<sg.length;l++)
                    {
                        if(reach[i-1][f][l])
                        {
                            dp[i][j][(l+d)%2][0]=Math.max(dp[i][j][(l+d)%2][0],dp[i-1][f][l][0]+sg[l]*(1-d)*inc);
                            dp[i][j][(l+d)%2][0]=Math.max(dp[i][j][(l+d)%2][0],dp[i-1][f][l][1]+sg[l]*(1-d)*inc);
                            dp[i][j][(l+d)%2][1]=Math.min(dp[i][j][(l+d)%2][1],dp[i-1][f][l][0]+sg[l]*(1-d)*inc);
                            dp[i][j][(l+d)%2][1]=Math.min(dp[i][j][(l+d)%2][1],dp[i-1][f][l][1]+sg[l]*(1-d)*inc);
                            reach[i][j][(l+d)%2]=true;
                        }
                    }
                }
            }
        }

        int ma=Integer.MIN_VALUE;
        for(int i=0;i<2;i++)
            for(int j=0;j<2;j++)
                if(dp[n][k][i][j]!=Integer.MAX_VALUE && dp[n][k][i][j]!=Integer.MIN_VALUE)
                    ma = Math.max(ma,dp[n][k][i][j]);
        System.out.println(ma);
    }
}

import java.util.Arrays;
import java.util.Scanner;

public class LogoTurtle {
    private static String input;
    private static int[][][][] dp;
    public static void main(String[] args) {
//        Scanner sc = new Scanner(System.in);
        Scanner sc = new Scanner("FFFTFFF\n2\n");
        input = sc.nextLine();
        int changes = sc.nextInt();

        dp = new int[2*(input.length()+1)][changes+1][2][input.length()+1];
        for (int i = 0; i < dp.length; i++) {
            for (int j = 0; j < dp[0].length; j++) {
                Arrays.fill(dp[i][j][0], -1);
                Arrays.fill(dp[i][j][1], -1);
            }
        }

        int res = Math.max(f(0, 0, true, changes), f(0, 0, false, changes));
        System.out.println(res);
    }
    private static int f(int cmdIndex, int pos, boolean direction, int changes) {
        int cached = dp[pos+input.length()][changes][direction?0:1][cmdIndex];
        if(cached != -1) {
            return cached;
        }

        int res = 0;

        // reached the end of the input
        if(cmdIndex == input.length()) {
            if(changes == 0) {
                res = Math.abs(pos);
            } else {
                res = -1;
            }
        } else {
            boolean isForward = input.charAt(cmdIndex)=='F';
            int delta = (direction?1:-1)*(isForward?1:0);

            // keeping the command
            int keepingNewPos = pos+delta;
            boolean keepingNewDirection = isForward?direction:!direction;
            int keeping = f(cmdIndex+1, keepingNewPos, keepingNewDirection, changes);

            // inverting the command
            int nonKeeping = -1;
            if(changes > 0) {
                int nonKeepingNewPos = pos+(direction?1:-1)*(!isForward?1:0);
                boolean nonKeepingNewDirection = (!isForward)?direction:!direction;
                int tmpChanges = changes;
                while(tmpChanges-1 >= 0) {
                    nonKeeping = Math.max(nonKeeping, f(cmdIndex+1, nonKeepingNewPos, nonKeepingNewDirection, tmpChanges-1));
                    tmpChanges -= 2;
                }
            }

            res = Math.max(keeping, nonKeeping);
        }

        dp[pos+input.length()][changes][direction?0:1][cmdIndex] = res;
//      System.err.printf("%d %d %d\n", pos+input.length(), changes, direction?0:1);
        return res;
    }
}

import java.io.*;
import java.util.*;

public class C {

	public C () throws IOException {
		char [] commands = sc.next().toCharArray();
		int N = sc.nextInt();
		print(solve(commands, N));
	}

	public int solve (char [] C, int N) {

		int L = C.length;
		char [] Z = new char [L];
		for (int i = 0; i < L; ++i)
			Z[i] = C[L-i-1];
		C = Z;

		while (N > 0) {
			// 1. All Fs
			String cmd = new String(C);
			if (cmd.indexOf('T') == -1) {
				C[0] = 'T';
				--N;
			}

			// 2. N == 1
			else if (N == 1) {
				int S = -1;
				for (int i = 0; i < L; ++i) {
					C[i] = ch(C[i]);
					S = Math.max(S, eval(C));
					C[i] = ch(C[i]);
				}
				return S;
			}

			else {
				int count = 0;
				for (int i = 0; i < L; ++i) {
					if (C[i] == 'T')
						++count;
				}

				// 3. N >= 2, just one T
				if (count == 1) {
					for (int i = 0; i < L; ++i) {
						if (C[i] == 'T')
							C[i] = 'F';
					}
					--N;
				} else {
					int S = 0, x = -1, y = -1, z = -1;
					for (int i = 0; i < L; ++i) {
						// Look for the best pair to change - prefer farther ones!
						for (int j = i+1; j < L; ++j)
							if (C[i] == 'T' && C[j] == 'T') {
								C[i] = ch(C[i]); C[j] = ch(C[j]);
								int E = eval(C);
								if (E >= S) {
									S = E; x = i; y = j;
								}
								C[i] = ch(C[i]); C[j] = ch(C[j]);
						}
						// Look for best single to change - prefer farther ones!
						if (C[i] == 'T') {
							C[i] = ch(C[i]);
							int E = eval(C);
							if (E >= S) {
								S = E; z = i;
							}
							C[i] = ch(C[i]);
						}
					}

					if (z >= 0) {
						char [] D = new char[L];
						for (int i = 0; i < L; ++i)
							D[i] = C[i];
						C[x] = C[y] = D[z] = 'F';
						return Math.max(solve(C, N-2), solve(D, N-1));
					} else {
						C[x] = C[y] = 'F';
						N -= 2;
					}
				}
			}
		}

		return eval(C);
	}

	int eval (char [] C) {
		int x = 0, d = 1;
		for (char c : C) {
			if (c == 'T')
				d = -d;
			if (c == 'F')
				x += d;
		}
		return Math.abs(x);
	}

	char ch (char X) {
		if (X == 'F') return 'T';
		else return 'F';
	}

	////////////////////////////////////////////////////////////////////////////////////

	static Scanner sc;
	static long t;

	static void print2 (Object o) {
		System.out.println(o);
	}

	static void print (Object o) {
		print2(o);
		//print2((millis() - t) / 1000.0);
		System.exit(0);
	}

	static void run () throws IOException {
		sc = new Scanner(System.in);
		new C();
	}

	public static void main(String[] args) throws IOException {
		run();
	}

	static long millis() {
		return System.currentTimeMillis();
	}
}

import java.util.*;
import java.io.*;
public class Main {
    static char[] arr;
    static int n;
    static int l;
   // static int [][] dp;
    // public static int solve(int i, int j){
    //     if(i>=l) return 0;
    //     if(j>=n) return 0;
    //     if(dp[i][j]!=-1) return dp[i][j];
    //     if(arr[i]=='F') return 1+solve(i+1,j);
    //     else {
    //         int take = dp[]
    //     }
    // }
  public static void main(String[] args) throws IOException,InterruptedException{
	BufferedReader	 br = new BufferedReader(new InputStreamReader(System.in));
	PrintWriter out = new PrintWriter(System.out);
     	// String s = br.readLine();
        // char[] arr=s.toCharArray();
        // ArrayList<Integer> arrl = new ArrayList<Integer>();
        // TreeSet<Integer> ts1 = new TreeSet<Integer>();
        // HashSet<Integer> h = new HashSet<Integer>();
        // HashMap<Integer, Integer> map= new HashMap<>();
        // PriorityQueue<String> pQueue = new PriorityQueue<String>();
        // LinkedList<String> object = new LinkedList<String>();
        // StringBuilder str = new StringBuilder();
         String s = br.readLine();
         arr=s.toCharArray();
         l = arr.length;
 	    StringTokenizer   st = new StringTokenizer(br.readLine());
 	       n = Integer.parseInt(st.nextToken());
 	      // dp = new int [55][1];
 	      // for(int i =0; i<55; i++){
 	      //     Arrays.fill(dp[i],-1);
 	      // }
 	      // int ans = solve(0,0);
 	      int ans =0;
 	      for(int i=0; i<l; i++ ){
 	          if(n<0) break;
 	          if(arr[i]== 'F') ans++;
 	          else{
 	              arr[i] = 'F';
 	              n--;
 	              i--;
 	          }
 	      }
 	      if(n%2==0)
 	       out.println(ans);
 	       else out.println(ans-1);
 	  out.flush();

	}}

import java.io.*;

public class B {
      private static StreamTokenizer in = null;
    private static PrintWriter out = null;

    static int nextInt() throws IOException {
        in.nextToken();
        return (int) in.nval;
    }

    static long nextLong() throws IOException {
        in.nextToken();
        return (long) in.nval;
    }

    static double nextDouble() throws IOException {
        in.nextToken();
        return (double) in.nval;
    }

    static String nextString() throws IOException {
        in.nextToken();
        return in.sval;
    }

    public static void main(String[] args) throws IOException {
        in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        out = new PrintWriter(System.out);
        // Here is the solution:
        String str = nextString();
        int n = nextInt();
        out.println(new B().solve(str, n));
        out.flush();
    }

    String string;
    private int doit(int p, int c, boolean d) {
        if (c < 0)
            return -1;
        if (p == 0) {
            if (c % 2 == 0)
                return 0;
            else
                return -1;
        }

        if (visit[p][c][d?0:1])
            return dp[p][c][d?0:1];

        int res = -1;
        if (string.charAt(p-1) == 'F') {
            res = Math.max(Math.abs(doit(p - 1, c, d) + (d ? 1 : -1)), doit(p - 1, c - 1, !d));
        } else {
            res = Math.max(Math.abs(doit(p - 1, c - 1, d) + (d ? 1 : - 1)), doit(p - 1, c, !d));
        }

        visit[p][c][(d?0:1)] = true;
        return dp[p][c][d?0:1] = res;
    }

    boolean[][][] visit;
    int[][][] dp;
    public int solve(String str, int n) {
        this.string = str;
        int len = str.length();
        visit = new boolean[len+1][n+1][2];
        dp = new int[len+1][n+1][2];
        return Math.max(doit(len, n, true), doit(len, n, false));
    }
}

import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.image.AreaAveragingScaleFilter;
import static java.lang.Math.*;
import java.lang.*;

public class Main {
    static FastScanner in;
    static PrintWriter out;
    public static void main(String[] args) throws FileNotFoundException {
        runIO(0);

        Task solver = new Task();
        solver.solve(1, in, out);
        out.close();
    }

    public static void runIO(int R) throws FileNotFoundException{
        if (R==1){
            in = new FastScanner(new File("input.txt"));
            out = new PrintWriter(new File("output.txt"));
        } else
        {
            in = new FastScanner(System.in);
            out = new PrintWriter(System.out);
        }
    }
}

class Task {
    final int N = 110;
    final int Inf = 1000000007;
    String S;
    int n;
    int B=0, aa=0;
    int m;
    int dp[][][] = new int[N][52][2];
    int ans=0;
    //Time Complexity must be O(N*N*M*2) ~ O(N*N*N)
    public final int calc(int pos, int remain, int s) {
        if (remain < 0) return -1000000000;
        if (pos == n && remain > 0) return -1000000000;
        if (pos == n && remain == 0) return 0;

        if (dp[pos][remain][s]!=0) return dp[pos][remain][s];
        char c = S.charAt(pos);

        int p=0;
        if (c=='F'){
            if (s==1) p = max(p, calc(pos+1, remain, s )-1); else
                p = max(p, calc(pos+1, remain, s)+1);
        } else p = max(p, calc(pos+1, remain, s^1));

        {
            for (int op=1; op<=1 && op<=remain; op++) {
                if (op % 2==1) {
                    if (c == 'F') {
                        p = max(p, calc(pos + 1, remain - op, s ^ 1));
                    } else {
                        if (s == 1) p = max(p, calc(pos + 1, remain - op, s) - 1);
                        else
                            p = max(p, calc(pos + 1, remain - op, s) + 1);
                    }
                } else
                {
                    p = max(p, calc(pos, remain-op, s));
                }
            }

        }
        //out.println(pos+" "+len+" "+remain+" "+s+" = "+p);
        if (remain % 2==m % 2) ans = Math.max(ans, p);
        dp[pos][remain][s]=p;
        return p;
    }

    public void solve(int testNumber, FastScanner in, PrintWriter out) {
        S = in.next();
        n = S.length();
        m = in.nextInt();
        boolean existsT = false;

        for (int i=1; i<=n; i++){
            char c = S.charAt(i-1);
            //for (int j)
            if (c=='T') existsT = true;
        }

        if (existsT==false && S.length()%2==0 && m==S.length()/2) out.println(S.length()); else {
            ans = Math.max(ans, calc(0, m, 0));
            for (int i=0; i<n; i++)
                for (int j=1; j<=m; j++)
                    for (int np=0; np<=1; np++)
                    if (j % 2==m % 2) ans = Math.max(ans, calc(i, j, np));
            out.println(ans);
        }

    }

}

class Pair implements Comparable<Pair>{
    public int first, second;
    Pair(){
        first=second=-1;
    }
    Pair(int a, int b){
        first = a; second=b;
    }
    @Override
    public int compareTo(Pair b){
        if (first<b.first) return 1; else
        if (first>b.first) return -1; else
        if (second<b.second)  return 1; else return -1;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        char c = (char)42;
        result = (int)(1L*first*second + first + second);
        if (second!=0) result+=first % second;
        if (first!=0) result+=second%first;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        Pair b = (Pair)obj;
        if (first==b.first && second==b.second) return true;
        return false;
    }

}

class PairComparator implements Comparator<Pair>{

    public int compare(Pair a, Pair b) {
        if (a.first<b.first) return 1; else
        if (a.first>b.first) return -1; else
        if (a.second<b.second)  return 1; else return -1;
    }
}

class FastScanner {
    BufferedReader br;
    StringTokenizer st;

    public FastScanner(File f) {
        try {
            br = new BufferedReader(new FileReader(f));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public FastScanner(InputStream f) {
        br = new BufferedReader(new InputStreamReader(f));
    }

    String next() {
        while (st == null || !st.hasMoreTokens()) {
            String s = null;
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (s == null)
                return null;
            st = new StringTokenizer(s);
        }
        return st.nextToken();
    }

    boolean hasMoreTokens() {
        while (st == null || !st.hasMoreTokens()) {
            String s = null;
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (s == null)
                return false;
            st = new StringTokenizer(s);
        }
        return true;
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }
}