MaPY
MaPY

Reputation: 351

NZEC error for ACODE spoj

I am solving the Acode problem of SPOJ.It is a simple Dp problem here

This is my solution:

//http://www.spoj.com/problems/ACODE/

import java.util.Scanner;
//import java.util.Math;
public class Acode {
  public static void main(String[] args)
   {
     Scanner sc = new Scanner(System.in);

     String encodedString = sc.next();
     while (!encodedString.equals("0")) {
       long number = numOfDecodings(encodedString);
       System.out.println(number);
       encodedString = sc.next();
     }

     return;

   }

    public static long numOfDecodings(String encodedString)
    {
         int lengthOfString = encodedString.length();
           long decode[] = new long[lengthOfString];

         decode[0] = 1;

         if (isCurrentTwoDigitsValid(encodedString, 1)) {
             decode[1] = 2;
         } else {
             decode[1] = 1;
         }

         for (int i=2; i<lengthOfString; i++) {
              if (isCurrentTwoDigitsValid(encodedString, i)) {
                   decode[i] = decode[i-2] + decode[i-1];
              } else {
                   decode[i] = decode[i-1];
              }
         }

         return decode[lengthOfString-1];
    }

    public static boolean isCurrentTwoDigitsValid(String encodedString, int startIndex)
    {
        char c1 = encodedString.charAt(startIndex);
        char c2 = encodedString.charAt(startIndex-1);

        if ( (c2=='1') || (c2=='2' && c1<='6')) {
           return true;
        } else {
           return false;  
        }

    }


}

But I am getting an NZEC error when I try to submit it.I tested it for large values too and it is not breaking.I am not understanding how else to improve it.

Upvotes: 1

Views: 57

Answers (1)

DAle
DAle

Reputation: 9117

  1. When input size is 1 you get an error in

    if (isCurrentTwoDigitsValid(encodedString, 1)) {
        decode[1] = 2;
    } else {
        decode[1] = 1;
    } 
    

    because of accessing out of the decode array bounds.

  2. You treat 0 as a valid number, but it's not. For example, the correct answer for input "10" is 1, not 2.

Upvotes: 1

Related Questions