-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestWord_IgnorePunctuation
109 lines (81 loc) · 1.82 KB
/
LongestWord_IgnorePunctuation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*Challenge
Have the function LongestWord(str) take the str parameter being passed and return the largest word in the string.
If there are two or more words that are the same length, return the first word from the string with that length.
Ignore punctuation and assume str will not be empty.
Sample Test Cases
Input:"fun&!! time"
Output:"time"
Input: "coding %$#pro$%%&$##"
Output: "coding"
*/
#include <iostream>
#include <string>
#include<vector>
#include <algorithm>
using namespace std;
vector<int> findSpaces(string str) {
vector<int> array;
int lastSpace = 0;
bool firstTime = false;
int counter = 0;
str += ' ';
for (int i = 0; i < str.length(); i++) {
if (str[i] == ' ') {
if (!firstTime) {
array.push_back(i - lastSpace - counter);
lastSpace = i;
firstTime = true;
counter = 0;
}
else {
array.push_back(i - lastSpace - 1 - counter);
lastSpace = i;
counter = 0;
}
}
}
return array;
}
int maxIndex(vector<int> array) {
int maxEl = -1;
int index = 0;
for (int i = 0; i < array.size(); i++) {
if (maxEl < array[i]) {
maxEl = array[i];
index = i;
}
}
return index;
}
bool isLetter(char c) {
if (c > 96 && c < 123 || c > 64 && c < 91)
return true;
return false;
}
void clear(string& str) {
for (int i = 0; i < str.size(); i++) {
if (!isLetter(str[i]) && str[i] != ' ') {
str.erase(std::remove(str.begin(), str.end(), str[i]), str.end());
i--;
}
}
}
string LongestWord(string str) {
clear(str);
vector<int> array = findSpaces(str);
if (array.size() == 1)
return str;
int index = maxIndex(array);
int start = 0;
for (int i = 0; i < index; i++) {
start += array[i] + 1;
}
string str1 = str.substr(start, array[index]);
return str1;
}
void main() {
string str;
getline(cin, str);
cout << LongestWord(str);
system("pause>0");
}