Portfolio

Highest_Scoring_Word


/*Given a string of words, you need to find the highest scoring word.

Each letter of a word scores points according to it's position in the alphabet: a = 1, b = 2, c = 3 etc.

You need to return the highest scoring word as a string.

If two words score the same, return the word that appears earliest in the original string.

All letters will be lowercase and all inputs will be valid.
*/

 

#include<iostream>
#include <string>
#include <vector>
using namespace std;

std::vector<std::string> split (std::string line){
int len = line.length();
vector<string> subArray;

for (int j = 0, k = 0; j < len; j++) {
if (line[j] == ' ') {
string ch = line.substr(k, j - k);
k = j+1;
subArray.push_back(ch);
}
if (j == len - 1) {
string ch = line.substr(k, j - k+1);
subArray.push_back(ch);
}
}
return subArray;
}

int suma (string vs){
int sum =0;
for(int i=0; i<vs.length(); i++) {
sum += (((int)vs[i])-96);
}
return sum;
}

std::string highestScoringWord(const std::string &str)
{

std::vector<string> v = split(str);
int tmp =0, max=0,j;
for(int i =0; i<v.size(); i++){
tmp=suma(v[i]);
if(tmp > max) {
max=tmp;
j=i;
}
}
return v[j];
}