class Solution {
public:
string reverseWords(string s) {
int previousWhiteSpace = 0;
for(int i = 0; i <= s.size(); i ++){
if(isspace(s[i]) || i == s.size()){
for(int j = previousWhiteSpace; j < i/2; j++){
char temp = s[j];
s[j] = s[i-1-j];
s[i-1-j] = temp;
}
previousWhiteSpace = i + 1;
}
}
return s;
}
};
Hi. So the goal of my function is to reverse the input of a string. So for example, if I am given "Let's take LeetCode contest" , my function should return "s'teL ekat edoCteeL tsetnoc" . However, currently my function is ONLY returning
"s'teL take LeetCode contest" . I have a counter which I indicate as previousWhiteSpace to keep track of the start of every new word that seems to work for the first word, but not the rest. Any help would be appreciated.
You can simply assign " " to the variable previousWhiteSpace and no need to increment. thus your code will detect white space automatically till the end of the string and will run the code after every white space. As you have assigned value 0 to it will only perform the result for the first word and it will terminate.
Related
So I have a code to decode an encoded string. The function has a list of numbers and another list with randomized letters.
The number list is a pointer that indicates which letter is first in an order. The problem is that the numbers are built using this code -
for (int i = 0; i < count; i++)
{
Random r = new Random();
int removeIndex = r.Next(0, splited.Count);
result.Add(splited[removeIndex]);
splited.RemoveAt(removeIndex);
pointers.Add(removeIndex);
}
So basically what happens for example :
Letters = { a, b, c, d}
Pointer = { 2, 0, 1, 0}
Result = { c, a, b, d}
The thing I want to happen is something like in
this example
or in this example
(Result is the requested return. Remaining code is what left in the randomized list.
Initial number and onward is the list generation process.)
What I've tried -
List<char> encodedToChar = new List<char>(encodedText);
List<char> encodedResult = new List<char>();
List<int> whereToRemove = new List<int>();
for (int i = 0; i < length; i++)
{
encodedResult.Add('☺');
}
Console.WriteLine();
Console.WriteLine();
for (int i = 0; i < length; i++)
{
whereToRemove.Add(pointerToInt[i]);
int addCurrentPos = -1;
for (int a = 0; a < whereToRemove.Count; a++)
{
if (pointerToInt[i] >= whereToRemove[a])
{
addCurrentPos++;
}
}
encodedResult[pointerToInt[i] + addCurrentPos] = encodedToChar[i];
Console.Write(" ' " + (int)(pointerToInt[i] + addCurrentPos) + " ' ");
for (int k = 0; k < length; k++)
Console.Write(" " + encodedResult[k]);
Console.Write(" : ");
}
This is the code in action.
which almost works. (Top numbers are pointers and below each pointer is the letter which should be in that position)
I've tried multiple solutions but can't figure one that works.
since the encoded code is made whilst removing the letter, one thing I can think of on how to get the exact position is to somehow count how many letters were removed but there are more problems, for example, if the last 2 remaining letters are the first letter and the last letter (which it is possible) , the pointer can show 0 , 0. and therefor you cant know which one is the last and which one is the first unless you use some kind of a trick which I cant figure out..
(Or maybe it's just not possible and I should change the code generation method)
I wrote a simple program to find the longest sub-string with distinct characters in a given string in C++. My code works for certain inputs, but doesn't for others. Moreover, it gives me different outputs for the same inputs. Where am I going wrong?
int main() {
int t;
cin >>t;
while(t--){
string s;
cin >> s;
int n = s.length();
int maxlen = 0;
for(int i = 0; i < n; i++){
int count = 0;
int arr[26] = {0};
bool isDist = true;
int j = i;
while(isDist){
if(arr[(int)s[j] - (int)'a'] == 0){
count++;
arr[(int)s[j] - (int)'a'] = 1;
j++;
} else {
isDist = false;
}
}
if(count > maxlen) maxlen = count;
}
cout << maxlen << endl;
}
return 0;
}
for the following input:
3
aewergrththy
aewergrththy
aewergrththy
My code outputs:
5
4
4
Any help is appreciated, Thank you!
The problem is that there is no check that j remains less than n, so you start checking characters beyond the end of your string, leading to in unpredictable results. Try
while (isDist && j < n)
That should help but I haven't checked the rest of your code for errors.
You could also consider using s.at(j) instead of s[j]. That at least results in predictable behaviour when going out of bounds, at throws an exception in that case.
The program has undefined behavior because you do not bounds-test when iterating over the string with j. You should modify the inner loop to test for j in addition to isDist:
while(isDist && j < n)
Without this, it's very easy for j to shoot past the end of the string as soon as all remaining characters in the string have not yet been encountered.
In this case, it will be when you process the character 'y' at the end of the string. After dealing with 'y', you'll advance j such that s[j] returns the string terminator. Now, you'll be accessing the array with arr[0 - 'y'] which of course is undefined behavior due to being a negative index.
I tried to write an algorithm to guess correctly in the game "Masterminds",
it works the average number of guesses is 6, but it takes a lot of time to calculate the best guess.
I used the idea of Knuth the algorithm works as follows:
Create the set S of 1296 possible codes (1111, 1112 ... 6665, 6666).
Start with initial guess 1122 (Knuth gives examples showing that other first guesses such as 1123, 1234 do not win in five tries on
every code).
Play the guess to get a response of colored and white pegs.
If the response is four colored pegs, the game is won, the algorithm terminates.
Otherwise, remove from S any code that would not give the same response if the current guess were the code.
In my code step 2 is to take random number.
I used vector<string> for this.
AllPoss is the vector full of strings, I guess is the last guess that was used. answer is the count of bulls and cows looks like "x,y" (where x and y are numbers)
void bullpgia::SmartGuesser::remove(string guess, string answer)
{
for (auto i= AllPoss.begin();i != AllPoss.end();i++){
string token = *i;
if (calculateBullAndPgia(token, guess) != answer)
AllPoss.erase(i--);
}
}
this is the part it take a lot of time to calculate is there any way of improvement?
to creating the list i used :
void bullpgia::SmartGuesser::All() {
/**
* creates a pool of all the possibilities strings
* we then delete the ones we dont need
* #param length is the length of the word we need to guess
*/
for(int i=0;i<pow(10,length);i++){
stringstream ss;
ss << setw(length) << setfill('0') << i;
string s = ss.str();
AllPoss.push_back(s);
}
}
the function calculateBullAndPgia(string , string) is:
string calculateBullAndPgia(const string &choice, const string &guess) {
string temp = choice;
string temp2 = guess;
unsigned int bull = 0;
unsigned int pgia = 0;
for (int i = 0; i < temp.length(); i++) {
if (temp[i] == temp2[i]) {
bull++;
temp[i] = 'a';
temp2[i] = 'z';
}
}
for (int i = 0; i < temp.length(); i++) {
for (int j = 0; j < temp2.length(); j++) {
if (i != j && temp[i] == temp2[j]) {
pgia++;
temp[i] = 'a';
temp2[j] = 'z';
}
}
}
return to_string(bull) + "," + to_string(pgia);
}
Erasing a single element in the middle of a vector is O(n). My guess is that you wind up doing it O(n) times per call to SmartGuesser::remove. Then you loop over that so you probably have a O(n^3) algorithm. You instead could use std::remove_if, which is O(n), to move all the to-be-erased elements to the end of the vector where they can be cheaply erased.:
AllPoss.erase(std::remove_if(AllPos.begin(), AllPos.end(), [&](const std::string& token, const std::string& guess) { return calculateBullAndPgia(token, guess) != answer; }), AllPos.end());
I am attempting to add space before a character in a string by using the insert function.
Can someone kindly explain why the following code does not work ?
for(int i = 0; i < line.length(); i++)
{
if(line[i+1] == '=')
{
line.insert(i, " ");
}
}
If you want to insert before = you can get the index of = directly and not the index of char followed by =. This could lead to out of bounds access.
Also, when you insert the space you extend your string by 1, that's ok but only if you also adjust the counter i, otherwise it will insert again and again and again before = resulting in infinite loop. Adjust your code in this manner:
for (int i = 0; i < line.length(); i++)
{
if (line[i] == '=')
{
line.insert(i++, " ");
}
}
The code seems fine except for one little detail:
Imagine you have a string with "test=something". When you iterate it, when i is 3 you will find the next character is an equals, so you put a space into it. Next iteration i will be 4, but you just added a space, so at i equals 5 there's the same equals sign. So you put another space and so on. TO fix this youy can try:
std::string line = "test=something";
for (int i = 0; i < line.length(); i++)
{
if (line[i + 1] == '=')
{
i++;
line.insert(i, " ");
}
}
I have written this function that reverses the order of words within a string, the function behaves as expected until it has read two words then starts to behave unexpectedly:
string ReverseString(string InputString){
int EndOfGroup = 0;
string ReversedString = " ";
int k = 0;
ReversedString.resize(InputString.size());
for (int i = InputString.length(); i > 0; i--){
if (isspace(InputString[i]))
{
EndOfGroup = i;
for (int j = i; j >= EndOfGroup && j < InputString.length(); j++)
{
ReversedString[k] = InputString[j] ;
k++;
}
}
}
What I mean by behaves unexpectedly is that once I pass a string to the function it starts to populate the ReversedString variable with garbage values until the goes out of bounds.
This shoes the point the programme crashes:
InputString "the brown fox died"
ReversedString " died fox died brownÍÍÍÍÍÍÍÍÍÍÍÍýýýý««««««««îþîþ"
j 9
i 3
EndOfGroup 3
k 20
This is not a duplicate question as my method is different to existing methods out there.
Think about the inner loop,
for (int j = i; j >= EndOfGroup && j < InputString.length(); j++)
For the first word, this is good, now for the second word - are the conditions correct?
Remember you are writing to the reversed string using an incrementing index k...
You are copying the word only when you are meeting space sign
if (isspace(InputString[i]))
{
//start of copying...
what does mean that you will not copy the first work (there is no space before the word).
resize() method is fullfilling the string will null character (due to reference) and they are probably show as
ÍÍÍÍÍÍÍÍÍÍÍÍýýýý««««««««îþîþ
You need to handle the first word
for (int i = InputString.length(); i >= 0; i--){
if (isspace(InputString[i]) || i == 0)
Also it would be good to provide some default char instead of null by using
ReversedString.resize(InputString.size(), ' ');