String Python C++

Jimmy (xiaoke) Shen
4 min readFeb 13, 2020

--

557. Reverse Words in a String III

Python is very easy

class Solution:
def reverseWords(self, s: str) -> str:
ss = s.split()
ss = [c[::-1] for c in ss]
return ' '.join(ss)

C++ similar idea and much longer as we have to write our own split and reverse code.

class Solution {
public:
string reverse(string s){
if(s.empty())return s;
string res = "";
while(!s.empty()){
res += s.back();
s.pop_back();
}
return res;
}
vector<string> split(string s){
vector<string> res;
if(s.empty())return res;
string temp = "";
for(int i=0;i<s.length();++i){
if(s[i]==' '){
res.push_back(temp);
temp="";
}
else temp+=s[i];
}
if(!temp.empty())res.push_back(temp);
return res;
}
string reverseWords(string s) {
vector<string> ss = split(s);
string res = "";
for(auto&s:ss){
res += reverse(s);
res += ' ';
}
res.pop_back();
return res;
}
};

Actually, C++ can use a more efficient way to solve this problem.

class Solution {
public:
string reverseWords(string s) {
auto size = s.size();
int from = 0;
for(int i = 1; i < size; ++i) {
if(s[i] == ' '){
reverse(begin(s)+from, begin(s)+i);
from = i+1;
}
}
reverse(begin(s)+from, end(s));
return s;
}
};

1047. Remove All Adjacent Duplicates In String

https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/

class Solution {
public:
string removeDuplicates(string S) {
//old_len = S.length();
while(true){
string new_S = "";
int i=0;
while(i<S.length()){
if(i+1<S.length() && S[i+1]==S[i]){
i += 2;
}
else{
new_S += S[i];
++i;
}
}
if (new_S.length()==S.length())return new_S;
S = new_S;
}
return "";

}
};

Better one from lee215

https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/discuss/294893/JavaC++Python-Two-Pointers-and-Stack-Solution

string removeDuplicates(string s) {
int i = 0, n = s.length();
for (int j = 0; j < n; ++j, ++i) {
s[i] = s[j];
if (i > 0 && s[i - 1] == s[i]) // count = 2
i -= 2;
}
return s.substr(0, i);
}

Or we can use stack

class Solution {
public:
string removeDuplicates(string S) {
string res = "";
for(auto&c:S){
if(res.size() && c==res.back())res.pop_back();
else res.push_back(c);
}
return res;
}
};

422. Valid Word Square

class Solution {
public:
bool validWordSquare(vector<string>& words) {
for(int i = 0; i < words.size(); ++i) {
for(int j = 0; j < words[i].size(); ++j)
if(j >= words.size()|| i>=words[j].size() || words[j][i] != words[i][j])
return false;
}
return true;
}
};

Python

class Solution:
def validWordSquare(self, words: List[str]) -> bool:
return words== [''.join(c) for c in itertools.zip_longest(*words,fillvalue='')]

387. First Unique Character in a String

class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char,int> m;
for (auto &c:s)m[c]++;
for(int i=0;i<s.length();++i){
if(m[s[i]]==1)return i;
}
return -1;

}
};

392. Is Subsequence

https://leetcode.com/problems/is-subsequence/

class Solution {
public:
bool isSubsequence(string s, string t) {
if(s.empty())return true;
if(t.empty())return false;
int j=0;
for(int i=0;i<t.size()&&j<s.size();++i)
if (t[i]==s[j])++j;
return j==s.size();
}
};

Binary search

class Solution {
public:
bool isSubsequence(string s, string t) {
if(s.empty())return true;
if(t.empty())return false;
vector<vector<int>> d(256);
for(int i=0;i<t.length();++i)d[t[i]].push_back(i);
int from = -1;
for(auto &c:s){
auto it = upper_bound(d[c].begin(), d[c].end(), from);
if (it==d[c].end())return false;
from = *it;
}
return true;
}

125. Valid Palindrome

https://leetcode.com/problems/valid-palindrome/

class Solution {
public:
bool isPalindrome(string s) {
string t="";
for(auto &c:s){
if (isalnum(c)){
if(isalpha(c))t.push_back(tolower(c));
else t.push_back(c);
}
}

/*
string tt=t;
reverse(t.begin(),t.end());
return tt==t;
*/
for (int i=0;i<t.size()/2;++i){
if(t[i]!=t[t.size()-i-1])return false;
}
return true;
}
};

Or do it like this

class Solution {
public:
bool isPalindrome(string s) {
for (int i = 0, j = s.size() - 1; i < j; i++, j--) { // Move 2 pointers from each end until they collide
while (!isalnum(s[i]) && i < j) i++; // Increment left pointer if not alphanumeric
while (!isalnum(s[j]) && i < j) j--; // Decrement right pointer if no alphanumeric
if (toupper(s[i]) != toupper(s[j])) return false; // Exit and return error if not match
}

return true;
}
};

1048. Longest String Chain

https://leetcode.com/problems/longest-string-chain/

https://leetcode.com/problems/longest-string-chain/discuss/294890/C%2B%2BJavaPython-DP-Solution

class Solution {
public:
int longestStrChain(vector<string>& words) {
unordered_map<string, int> dp;
for(auto &word:words) dp[word] = 1;
sort(words.begin(), words.end(), [](string &a, string &b){
return a.length()<b.length();
});
for(auto &word:words){
for(int j=0; j <word.length();++j){
string new_word = word.substr(0,j)+word.substr(j+1);
if(dp.count(new_word))dp[word] = max(dp[word], dp[new_word]+1);
}
}
int res = 0;
for(auto& d:dp)res=max(res, d.second);
return res;
}
};

Python code

class Solution:
def longestStrChain(self, words: List[str]) -> int:
dp = {}
for word in sorted(words, key=len):
dp[word] = max(dp.get(word[:i]+word[i+1:], 0)+1 for i in range(len(word)))
return max(dp.values())

451. Sort Characters By Frequency

32 ms

class Solution:
def frequencySort(self, s: str) -> str:
return ''.join(c*freq for c, freq in collections.Counter(s).most_common())

16 ms

class Solution {
public:
string frequencySort(string s) {
unordered_map<char,int> freq;
vector<string> bucket(s.size()+1, "");
string res;

//count frequency of each character
for(char c:s) freq[c]++;
//put character into frequency bucket
for(auto& it:freq) {
int n = it.second;
char c = it.first;
bucket[n].append(n, c);
}
//form descending sorted string
for(int i=s.size(); i>0; i--) {
if(!bucket[i].empty())
res.append(bucket[i]);
}
return res;
}
};

--

--

No responses yet