(SPOJ) Edit Distance Again - Solution 2

Link to the problem: http://www.spoj.com/problems/EDIT/

If you want to see another solution for this problem, click here.

The solution below used a Greedy approach to solve this problem.


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

class Main {
    public String s;
   
    public void process() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
                     
        s = br.readLine();
        while (s != null) {
            int sumChanges1 = 0;
            int last = (s.charAt(0) >= 'A' && s.charAt(0) <= 'Z') ? 1 : 0; // 1 -> upper , 0 -> lower
            for (int i = 1; i < s.length(); i++) {
                int curr = (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') ? 1 : 0;
                if (last == curr) {
                    sumChanges1++;
                    last = (curr+1)%2;
                    continue;
                }
                last = curr;
            }
           
            int sumChanges2 = 1; // changed the first character (see the next line)
            last = (s.charAt(0) >= 'A' && s.charAt(0) <= 'Z') ? 0 : 1; // 1 -> upper , 0 -> lower
            for (int i = 1; i < s.length(); i++) {
                int curr = (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') ? 1 : 0;
                if (last == curr) {
                    sumChanges2++;
                    last = (curr+1)%2;
                    continue;
                }
                last = curr;
            }
           
           
            bw.write(Math.min(sumChanges1, sumChanges2)+"\n");
              
            s = br.readLine();    
        }
       
        bw.flush();
        bw.close();
                 
        return;
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();
       
        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução

(CoderByte) Number Search - Solução