CH 7 [Strings]
CH 7 [Strings]
Strings
• String is a sequence of characters, for e.g. “Hello” is a string of 5 characters.
o String
o StringBuffer
o StringBuilder
Program:
Output:
the string.
charAt(int index) char The charAt() method is used to return
the character at the specified position.
deleteCharAt(int index) StringBuilder The deleteCharAt () method is used to
delete the character at specified index
length() int The length() method is used to return
the length of the string i.e. total
number of characters.
substring(int beginIndex) String The substring() method is used to
return the substring from the specified
beginIndex.
substring(int beginIndex, int endIndex) String The substring() method is used to
return the substring from the specified
beginIndex and endIndex.
toString() String The toString() method to get string
representation of an object.
Program:
Output:
Palindrome String
A palindrome string is one which reads the same when it is reversed.
Approach:
• Traverses the input string forwards and backwards, and compare the each character.
Program:
import java.util.Scanner;
str = str.toLowerCase();
if(flag)
else
if (s.charAt(i) != s.charAt(j)) {
return false;
}
}
return true ;
}
}
Output:
Case 1:
Enter a string to check palindrome or not: Madam
String madam is palindrome.
Case 2:
Enter a string to check palindrome or not: Sir
String sir is not palindrome.
• The time complexity is O(n) and the space complexity is O(1), where n is the length of
the string.
Write a program to convert a given string to an integer without using any in-built
functions.
For example:
o If user inputs "321", then the program should give output 321 as an
integer number.
o If user inputs "-321", then the program should give output -321 as an
integer number.
Program:
import java.util.Scanner;
if (strNum.charAt(i) == '-') {
else {
//converting each character into ASCII format and form the number.
//Minus the ASCII code of '0' to get the numeric value of the charAt(i)
final int digit = (int)( strNum.charAt(i) - '0');
}
}
//if the first character is '-', i.e., isNegative is true, then adds the
// negative sign to the result and return it otherwise return result
if (isNegative) {
return - result;
}
else {
return result;
}
}
}
Output:
Case 1:
Case 2 :
• The time complexity is O(n) and space complexity is O(1). Here n is the string length.
Write a program to convert a given integer number to string, without using inbuilt method
i.e., parseInt() and valueOf() in java.
For example:
o If user inputs 871, then the program should give output “871” as a
string number.
o If user inputs -871, then the program should give output “-871” as a
string number.
Program:
import java.util.Scanner;
isNegative = true;
}
} while(num != 0);
//if the num is negative number then adds the negative sign
if (isNegative) {
sb.append('-') ;
}
Output:
Case 1:
Case 2 :
• The time complexity is O(n) and space complexity is O(n). Here n is the number of digits
in input number and/or output string length.
BASE CONVERSION
In Computer Science, quite often, we are required to convert numbers from one base to another.
The commonly used number systems are binary numbers system (i.e., bases 2), octal numbers
system (i.e., bases 8), decimal numbers system (i.e., bases 10) and hexadecimal numbers system
(i.e., bases 16).
Binary numbers include digits 0 and 1, and so they have base 2. Octal numbers have digits from
0 to 7, thus having base 8. Decimal numbers have digits from 0 to 9, thus have base 10. And
hexadecimal numbers have digits from 0 to 9 and then A to F, thus having base 16.
In the decimal number system, the position of a digit is used to signify the power of 10 that digit
is to be multiplied with. For example, "314" denotes the number 3 X 100 +1 X 10 + 4 X 1. The
base b number system generalizes the decimal number system: the string "an – 1 an - 2 ... a1 a0",
where 0 < ai < b, denotes in base-b the integer an -1 X bn -1+ an - 2 X bn - 2...a1 X b1+ a0 X b0.
Write a program in Java to convert a number in any base into another base, limiting the
base value up to 16. The input is a string, an integer b1, and another integer b2. The string
represents be an integer in base b1. The output should be the string representing the integer
in base b2. Assume 2 ≤ b1, b2 ≤ 16. Use "A" to represent 10, "B" for 11, ..., and "F" for 15.
(For example, if the string is "615", b1 is 7 and b2 is 13, then the result should be "1A7",
since 6 x 72 + 1 x 7 + 5 = 1 x 132 + 10 x 13 + 7).
Approach:
• Then convert that decimal integer value to a string in base b2 using a sequence of
modulus and division operations.
Example:
Program:
import java.util.Scanner;
System.out.println("The base " + b1 + " equivalent of " + strNumb1 + " in base "
+ b2 + " is " + strNumb2);
}
//initialization
int numAsInt = 0;
int digit = 0;
else {
return ("0");
}
else {
//if the first character is '-', i.e., isNegative is true then adds
//negative sign to the result and return it; otherwise return result.
//The result is found by Converting the decimal value to base b2
if (isNegative) {
else {
if (numAsInt == 0) {
else {
//If the remainder is >= 10 or not
if(numAsInt % base >= 10) {
else {
// If the remainder is a digit < 10, simply add it
return (constructFromBase(numAsInt / base, base)
+ (char)('0' + numAsInt % base));
}
}
}
}
Output:
Case 1:
Case 2:
Case 3:
• The time complexity is (𝑛(1 + log b2 𝑏1 )) , where n is the length of string. The reasoning
is as follows. First, we perform n multiply-and-adds to get decimal integer, i.e., x from
string. Then we perform log b2 𝑥 multiply and adds to get the result. The value x is upper-
bounded by 𝑏1𝑛 , and 𝑙𝑜𝑔𝑏2 (𝑏1𝑛 ) = 𝑛 𝑙𝑜𝑔𝑏2 𝑏1
Spreadsheets or excel sheet often use an alphabetical encoding of the successive columns.
Specifically, columns are identified by "A", "B", "C", . . ., "X", "Y", "Z", "AA", "AB", ..., "ZZ",
"AAA", "AAB",.... and so on.
Approach:
Therefore,
1 X 261 + 2 X 260
= 1 X 26 + 2 X 1
= 26 + 2
= 28
Therefore,
Program:
import java.util.Scanner;
//Initialization
int result = 0;
return result;
}
}
Output:
Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.
Implement
a function that converts an integer to the spreadsheet column id. For example, you
should return "D" for 4, "AA" for 27, and "ZZ" for 702.
Approach:
Example:
r = 25 % 26 = 25
n = (25 / 26) = 0, result += 'A' + (25 - 1) = 'Y'
n = 0, stop,
output reverse("ZY") = "YZ"
r = 38 % 26 = 12
n = (38 / 26) = 1, result += 'A' + (12 - 1) = 'L'
r = 1 % 26 = 1
n = (1 / 26) = 0, result += 'A' + (1 - 1) = 'A'
n = 0, stop,
output reverse("LLA") = "ALL"
Write a program which takes as input an array of characters, and removes each entry
containing 'b' and replaces each 'a' by two 'd's. Specifically, along with the array, you are
provided an integer-valued size. Size denotes the number of entries of the array that the
operation is to be applied to. You do not have to worry preserving about subsequent
entries. Furthermore, the program returns the number of valid entries.
Example, if the array is < a, b, a, c,’ ’,’ ’,’ ’ > and the size is 4, then the program should
return the array < d, d, d, d, c >.
Approach:
• First, delete 'b's and compute the final number of valid characters of the string, with a
forward iteration through the string.
• Then replace each 'a' by two 'd's, iterating backwards from the end of the resulting string.
• If there are more 'b's than 'a's, the number of valid entries will decrease.
• If there are more 'a's than 'b's the number will increase.
Program:
char arr[] = {'a', 'b', 'a', 'c', ' ' , ' ',' ' };
int size = 4;
System.out.println(" ");
if (s[i] != 'b') {
s[writeldx++] = s[i];
if (s[i] == 'a') {
++aCount ;
}
}
// Backward iteration: replace "a"s with "d d"s starting from the end.
int curldx = writeldx - 1;
if (s[curldx] == 'a') {
else {
--curldx ;
return finalSize;
}
}
Output:
• The forward and backward iteration search take O(n) time, so the total time complexity is
O(n). No additional space is allocated.
TEST PALINDROMICITY
• A sentence can be defined as to be a palindrome string that reads the same thing forward
and backward, after removing all the non-alphanumeric and ignoring case.
o The sentence "A man, a plan, a canal, Panama." is palindrome, because after
removing all the non-alphanumeric and ignoring case (here making lowercase) the
sentence is turned as “amanaplanacanalpanama”; when you read it forward and
backward, it is same.
o The sentence "Ray a Ray" is not a palindrome, because after removing all the
non-alphanumeric and ignoring case (here making lowercase) the sentence is
turned as "RayaRay"; when you read it forward and backward, it is not same.
Write a program to check if a sentence is a palindrome or not. You can ignore white spaces
and other characters to consider sentences as palindrome.
Approach:
• One index is pointing to the 1st character (i.e., i = 0) of the sentence to move forward and
another index is pointing to the last character (i.e., j = string length - 1) of the sentence to
move backward, skipping non-alphanumeric characters, performing case-insensitive
comparison on the alphanumeric characters.
• Return false as soon as there is a mismatch, means sentence is not palindrome. If the
indices cross, return true, means sentence is palindrome.
Program:
import java.util.Scanner;
if(flag)
System.out.println("Sentence is palindrome");
else
++i ;
}
--j ;
}
return false;
}
Output:
• Spend 0(1) per character and the sentence has n characters, so the time complexity is
O(n). The space complexity is O(1).
A sentence is given which containing a set of words and the words are separated by whitespace.
Reverse all the words in a sentence means transform that sentence in such a way so that the
words appear in the reverse order.
Example,
Let the sentence is "Alice likes Bob", transforms to "Bob likes Alice".
Approach:
• However, the words with more than one character, their letters appear in reverse
order.
Example:
• Reversing the whole sentence, the obtained reverse sentence is “boB sekil ecilA”.
• By reversing each word in reverse sentence, obtain the final result, “Bob likes Alice”.
Program:
import java.util.Scanner;
int start = 0;
return ;
}
if (array[i] == c) {
return i ;
}
}
return -1;
}
}
Output:
• The time complexity is O(n), where n is the length of the of the string. The additional
space complexity is O(1).
• Roman numerals are a number system developed in ancient Rome where letters represent
numbers.
o Although, it's a non-positional numeral system but there is an additional rule that
modify the value of a digit according to its place.
▪ That rule forbids the use of the same digit 3 times in a row. That's why 3 is
III
• The Roman number symbols to be a valid Roman Number, if symbols appear in non
increasing order with the following exceptions allowed:
o X placed before L or C indicates ten less, so 40 is XL (10 less than 50) and 90 is
XC (ten less than a hundred).
o C placed before D or M indicates a hundred less, so 400 is CD (100 less than 500)
and 900 is CM (100 less than 1000).
• Note: Back-to-back exceptions are not allowed, e.g., IXC and CDM are invalid.
• A valid complex Roman number string represents the integer which is the sum of the
symbols that do not correspond to exceptions; for the exceptions, add the difference of
the larger symbol and the smaller symbol.
Write a program which takes as input a valid Roman number string and returns the
corresponding integer.
Approach:
• Performs the right-to-left iteration, and if the symbol after the current one is greater than
it, then subtract the current symbol.
Program:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
HM.put('I', 1);
HM.put('V', 5);
HM.put('X', 10);
HM.put('L', 50);
HM.put('C', 100);
HM.put('D', 500);
HM.put('M', 1000);
sum -= HM.get(RomNum.charAt(i));
} else {
sum += HM.get(RomNum.charAt(i));
}
}
return sum;
}
}
Output:
• The overall time complexity is O(n), because for each character of string is processed in
O(1) time, where n is the length of the string. The Space complexity is O(1).
e ˽ l
H l o W r d Here ˽ denotes
l o ! a blank
• From the sinusoidal fashion of the string, it is possible to write the snakestring.
• To write the snakestring of the string, write the sequence from left to right and from top
to bottom in which the characters appear in the sinusoidal fashion of the string.
• Example :
Write a program which takes as input a string and returns the snakestring of the inputted
string.
Approach:
• It can be observed that, write the given string in a sinusoidal manner in the array, which
is shown below. Finally, for snakestring read out the non-null characters in row-manner.
0 e ˽ l
1 H l o W r d Here ˽ denotes
2 l o ! a blank
0 1 2 3 4 5 6 7 8 9 10 11
• However, it observe that the result begins with the characters s[l], s[5], s[9],..., followed
by s[0],s[2], s[4],..., and then s[3], s[7], s[11],…
• Hence, create snakestring directly (without writing string in a sinusoidal manner) with 3
iterations through given input string.
Program:
import java.util.Scanner;
Output:
• Let n be the length of s. Each of the three iterations takes0(n) time, implying an0(n)time
complexity.
• Specifically, to generate an entry of the sequence from the previous entry, read off the
digits of the previous entry, counting the number of digits in groups of the same digit.
o Fourth term is "1211", generated by reading third term as "One 2 One 1"
o Fifth term is “111221” generated by reading the forth term as “one 1 one 2 two 1”
o and so on.
Write a program that takes as input an integer n and returns the nth integer in the look-
and-say sequence. Return the result as a string.
Example:
• Let n = 4, then return the 4th term of the look and say sequence. Hence the sequence is
1211.
Program:
import java.util.Scanner;
System.out.println(" ");
System.out.println("The " + num + " term of the look and say sequence is " + result);
System.out.print("The look and say sequence are " + str + ' ');
str = nextNumber(str);
return str;
}
++i ;
++count ;
}
return result.toString();
}
Output:
Enter an Integer : 4
The look and say sequence are 1 11 21 1211
The 4 term of the look and say sequence is 1211
• Since there are n iterations and the work in each iteration is proportional to the length of
the number computed in the iteration, a simple bound on the time complexity is 0(n2).
• This repeating string, called a run, is typically encoded into two bytes.
• The first byte represents the number of characters in the run and is called the run count.
• The second byte is the value of the character in the run and is called the run value.
• Example:
Run length decoding is a process of interpretation and translation of coded information into a
comprehensible form.
To generate the decoded string, need to convert this sequence of digits into its integer equivalent
and then write the character that many times. do this for each character.
Approach:
1. Start with an empty string for the code, and start traversing the string.
2. Pick the first character and append it to the code.
3. Now count the number of subsequent occurances of the currently chosen character and
append it to the code.
4. When you encounter a different character, repeat the above steps.
5. In a similar manner, traverse the entire string and generate the code.
Given an input string, write a function that returns the Run Length Encoded string for the
input string. Assume the string to be encoded consists of letters of the alphabet, with no
digits.
Program:
import java.util.Scanner;
sb.append(count);
sb.append(str.charAt(i - 1));
++count ;
}
}
return sb.toString();
}
}
Output:
Given an input Run Length Encoded string, consisting of digits and lowercase alphabet
characters write a function that returns the decoded string. The decoded string is
guaranteed not to have numbers in it.
Program:
import java.util.Scanner;
int count = 0;
char c = s.charAt(i);
if (Character . isDigit(c)) {
result.append(c);
count -- ;
}
}
}
return result.toString();
}
}
Output:
• The IP address 0.011.255.245 is invalid, due to leading 0 present in the second decimal
number, i.e., 011.
• The IP address 192.168.1.312 is invalid, because the fourth decimal number, i.e., 312 is
beyond the range 0 to 255.
Let the given decimal string. A decimal string is a string consisting of digits between 0 and
9. Write a program that determines where to add periods to a decimal string so that the
resulting string is a valid IP address. There may be more than one valid IP address
corresponding to a string, hence return all possible valid IP addresses that can be obtained.
Example:
Approach:
• There are three periods in a valid IP address, hence enumerate all possible placements of
these periods, and check whether all four corresponding substrings are between 0 and
255. It is possible to reduce the number of placements by spacing the periods 1 to 3
characters apart. It is also potential to lead by stopping as soon as a substring is invalid.
• Example:
o Let the string is "19216811", one could put the first period after "1", "19" and
"192". If the first part is "1", after placing the second period, the second part
might be "9", "92" and "921". Amongst these, "921" is illegal, so do not go on
with it.
Program:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
System.out.println(ip);
if (isValidPart(first)) {
if (isValidPart(second)) {
} //end if
} //end for
} //end if
} //end for
} //end if
} //end for
return result;
}
return false;
}
return false;
}
Output:
19.216.81.1
192.1.68.11
192.16.8.11
192.16.81.1
192.168.1.1
• The total number of IP addresses is a constant (232), implying an (9(1) time complexity
for the above algorithm.