Hi,
I thought it's time to me to learn C++. To train, I've took a look at TopCoder and just found this exercise ( SRM 100 - Motorola Single Round Match 100 Round 1 - Division II, Level One,
Link):
Problem Statement
A letter-string is composed of letters ('A'-'Z','a'-'z') and dashes ('-'). The length of a letter-string is the number of characters in it not including dashes (in other words, the number of letters in the string). Given a list of letter-strings you will return the sum of their lengths.
Create a class LetterStrings that contains the method sum, which takes a String[], s, and returns an int representing the sum of the lengths of the given letter-strings.
Definition
Class: LetterStrings
Method: sum
Parameters: String[]
Returns: int
Method signature: int sum(String[] s)
(be sure your method is public)
Constraints
- s will contain between 1 and 50 elements, inclusive.
- Each element of s will have length between 1 and 50, inclusive.
- Each element of s will contain only letters ('A'-'Z','a'-'z') and dashes ('-').
Examples
0)
{\"-\"}
Returns: 0
1)
{\"A\"}
Returns: 1
2)
{\"-----Abc\"}
Returns: 3
3)
{\"-A-B-C-D\", \"--------EFGHI\", \"JKLMNOPQR\", \"---STU-VW-XYZ\"}
Returns: 26
Now I've created this piece of code:
#include <iostream>
#include <string>
using namespace std;
class LetterStrings {
public:
int sum(string s[]);
};
int LetterStrings::sum(string s[])
{
int summe = 0;
for(int el=0; s[el] != \"0\"; el++){
for(int i=0; i < s[el].length(); i++){
if( isalpha(s[el][i]) ) {
summe += 1;
}
}
}
return summe;
}
int main()
{
LetterStrings a, b;
string str[5] = {\"-A-B-C-D\", \"--------EFGHI\", \"JKLMNOPQR\", \"---STU-VW-XYZ\"};
cout << a.sum(str) << endl;
}
It seems to work, but I'm not quite sure if it fits the requirements (Method signature: int sum(String[] s)?)
What could be done better in this code?
edit: Just found the
statistics with the top-solution:
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <cmath>
#include <cctype>
#include <cstdio>
#include <utility>
using namespace std;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define VI vector<int>
#define VVI vector<vector<int> >
#define VS vector<string>
#define si size()
#define len length()
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class LetterStrings
{
public:
int sum(vector <string> s)
{
int ret=0;
for(int c=0;c<s.si;c++)
for(int d=0;d<s[c].len;d++)
if(isalpha(s[c][d]))
ret++;
return ret;
}
};
// Powered by PopsEdit
isalpha is obviously better then my check via ASCII-Table codes (I've edited my solution), but the top-solutions seems to include quite a lot which isn't needed.