19. Strings (LB)
Character Array-
1. We use 1d character array to simulate strings, e.g.,
char ch[10];cin>>ch;
2. string ends with '\0'
3. cin with string works only if till space, tab or new line is absent in input...
4. work with character array just like a normal array, here only datatype is changed to char, else wise it is just an array
--------------------------------------------
--------------------------------------------
5. In-Built functions-
- int n = strlen(ch)
- strcmp(s1,s2) // gives 0 if both strings are equal - strcpy(dest,source) // copies a string from dest to source
--------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------
STRING-
It is a C++ STL
1. has dynamic size (can dynamically increase size when needed)
2. null terminator (\0) NOT required
3. Has built-in functions:
- return s.size()
- return s == "hello"
- return s.size()
- return s == "hello"
- return s + "world"
- return s1.find(s2) // checks if given string has a substring or not, we get a starting idx from where substring s2 is found in string s1, if not found it returns string::npos
- s.erase(pos, len) // erase a substring
- s.push_back(ch)
- s.pop_back()
- s.insert(pos,ch)
- s.substr(pos,len)
- stoi(s)
- return s1.find(s2) // checks if given string has a substring or not, we get a starting idx from where substring s2 is found in string s1, if not found it returns string::npos
- s.erase(pos, len) // erase a substring
- s.push_back(ch)
- s.pop_back()
- s.insert(pos,ch)
- s.substr(pos,len)
- stoi(s)
---------------------------------------------------------------------------------------------------------------------------
1. Reverse a sentence-
the sky is blue --> blue is sky the
-------------------------------------------------------------------------------------------------------------
3. Removing substring from a string-
-------------------------------------------------------------------------------------------------------------------------
4. Check if s1 is any permutation of s2
Brute- sort both the strings and see if they are equal strings or not (nlogn)
Brute- sort both the strings and see if they are equal strings or not (nlogn)
Optimal- check if they have same character frequencies (n)
-------------------------------------------------------------------------------------------------------------------------
5. Check if any SUBSTRING of s1 is a permutation of s2
SLIDING WINDOW approach
------------
1. Count frequency of characters in
s1 (smaller string)
2. Traverse s2 (larger string) using a window of size = len(s1)
3. Maintain another frequency array for current window4. If both freq arrays match → permutation found





Comments
Post a Comment