CP190-CP0
Topic 7: String
Ninghui Li
Purdue University
ASCII Code
String Class for Doubles
Abstract Data Type
In computer science, an abstract data type (ADT) is defined by its behavior (semantics) as a number of public methods.
The internal implementation of these methods are hidden.
When using a data type, one needs to be aware of only the public methods.
For example, we use vector is a template abstract data type.
Implement a class with the following public interface
class mystr {
public:
mystr(string s)
mystr(double val, int precision)
double double_val()
vector<mystr> split(const char delim = ' ')
friend ostream& operator<<(ostream& os, const mystr& s);
};
ostream& operator<<(ostream& os, const mystr& s) {
// ...
}
Constructors and member initializer lists
/* creates a new mystr object from a string object */
mystr(string s) : d(s.size()) {
for (int i=0; i<s.size(); i++) d[i] = s[i];
}
/* create a new mystr object that contains string representation
of a double value, with a fixed number of digits after the
decimal point. */
mystr(double val, int precision) : d(1, '0') {
}
Parsing a string into a double
double double_val() {
double res = 0, div = 1;
int idx = 0, len = d.size();
bool neg = false;
if (d[0] == '-') { neg = true; idx++; }
while ('0' <= d[idx] && d[idx] <= '9') {
res = res * 10 + d[idx++] - '0';
}
if (idx < d.size() && d[idx++] == '.') { // has fraction
while ('0' <= d[idx] && d[idx] <= '9') {
res += (d[idx++] - '0') / (div *= 10);
}
}
return neg ? -res : res;
}
Stable Log Rearrange
Try solve it first
See Video and Provided Solution
Example: LeetCode
Solution Code (1)
class Solution {
public:
string findReplaceString(string S, vector<int>& indexes,
vector<string>& sources, vector<string>& targets)
{
vector< pair<int,int> > ops;
for (int i=0; i<indexes.size(); i++)
ops.push_back(make_pair(indexes[i], i));
sort(ops.begin(), ops.end());
string ans; int idx = 0;
for (auto& op : ops) {
int pos = op.first, j = 0, k = op.second;
if (pos > idx) ans.append(S, idx, pos-idx);
idx = pos;
string& p = sources[k], t = targets[k];
for ( ; j<p.length(); j++, pos++) {
if (S[pos] != p[j]) break;
}
if (j == p.length()) { // match
ans.append(t); idx += p.length();
}
}
ans.append(S, idx, S.length()-idx);
return ans;
}
};
End of Topic 7