Categories: Data Structure

DSA: Strings Concept

What is a String?

A string is a character sequence in computer science. It’s one of the most used data types in programming, and it’s used to represent text like names, addresses, and messages.

Storage:

A string is normally stored in memory as a contiguous block of memory holding the character sequence. Depending on the character encoding used, each character in the string is saved as a single byte or many bytes. It is vital to remember that because strings are normally immutable, any changes to a string result in the creation of a new string object in memory.

Declaration of Strings in various languages:
  1. C/C++: In C and C++, strings are represented as arrays of characters. To declare a string variable, use the following syntax:
char myString[] = "Hello, world!";

This creates a character array named myString that contains the string “Hello, world!”.

  1. Java: In Java, strings are represented as objects of the String class. To declare a string variable, use the following syntax:
String myString = "Hello, world!";

This creates a String object named myString that contains the string “Hello, world!”.

  1. Python: In Python, strings are represented as objects of the str class. To declare a string variable, use the following syntax:
my_string = "Hello, world!"

This creates a str object named my_string that contains the string “Hello, world!”.

String operations:

Here are some common string operations and their corresponding code examples:

  • Concatenation: String concatenation is the process of joining two or more strings together to form a new string.Example:
String firstName = "John"; 
String lastName = "Doe"; 
String fullName = firstName + " " + lastName;
  • String Length: String length is the number of characters in a string.Example:
String str = "Hello, World!"; 
int length = str.length();
  • Comparison: String comparison is used to compare two strings and check if they are equal or not.Example:
String str1 = "Hello"; 
String str2 = "hello"; 
boolean isEqual = str1.equalsIgnoreCase(str2);
  • Substring: Substring is a part of a string that is a contiguous sequence of characters.Example:
String str = "Hello, World!"; 
String substr = str.substring(7, 12);
  • String Search: String search is used to find the index of a substring within a string.Example:
String str = "Hello, World!"; 
int index = str.indexOf("World");
  • String Replace: String replace is used to replace one character or substring with another. Example:
String str = "Hello, World!"; 
String newStr = str.replace("World", "Universe");

Note: few concepts used further-

  • Palindrome: A palindrome is a string that remains the same even when its letters are reversed. For example, “racecar” is a palindrome.
  • Subsequence: A subsequence of a string is a sequence of characters that can be derived from the original string by deleting some or no characters without changing the order of the remaining characters. For example, “abc” is a subsequence of “aabbcc”.
  • Substring: A substring of a string is a contiguous sequence of characters within the string. For example, “def” is a substring of “abcdef”.
  • Binary string: A binary string is a string consisting of only two characters, typically “0” and “1”. These types of strings are commonly used in computer science, especially in algorithms related to binary trees and binary search.

There are also several library functions for Strings used in different programming languages(Java, C, C++, Python, etc).

Problems based on String Concept:

Given a string S, check if it is palindrome or not.

Example:

Input: S = "abba"
Output: 1
Explanation: S is a palindrome

Solution:

class Solution {
    int isPalindrome(String S) {
        // code here
        String n="";
        for(int i=S.length()-1;i>=0;i--){
            n=n+S.charAt(i);
        }
        if(n.compareTo(S)==0)
        return 1;
        else 
        return 0;
    }
};

Time Complexity: O(Length of S)
Space Complexity: O(1)

The function works as follows:

  1. It creates an empty string n.
  2. It iterates through the characters of S in reverse order, appending each character to n to create a reversed copy of S.
  3. It then compares the reversed string n to the original string S.
  4. If they are equal, the function returns 1 (indicating that S is a palindrome).
  5. If they are not equal, the function returns 0 (indicating that S is not a palindrome).

Given a string, The task is to count the number of alphabets present in the string.

Example:

Input:
S = "adjfjh23"
Output: 6
Explanation: only last 2 are not 
alphabets.

Solution:

class Solution{
    static int Count(String S)
    {int count=0;
        // code here
        for(int i=0;i<S.length();i++){
            char c=S.charAt(i);
            if(Character.isLetter(c))
            count++;
        }
        return count;
    }
}

Time Complexity: O(Length of S)
Space Complexity: O(1)

The function works as follows:

  1. The method Count takes a string S as input and returns an integer value.
  2. It initializes a variable count to zero to count the number of letters.
  3. A for loop iterates over all the characters in the string S.
  4. For each character, it checks if it is a letter or not using the Character.isLetter() method.
  5. If the character is a letter, it increments the count variable.
  6. Once the loop is complete, the method returns the final count value.

Bingu was testing all the strings he had at his place and found that most of them were prone to a vicious attack by Banju, his arch-enemy. Bingu decided to encrypt all the strings he had, by the following method.

Every substring of identical letters is replaced by a single instance of that letter followed by the number of occurrences of that letter. Then, the string thus obtained is further encrypted by reversing it.

Example:

Input:
s = "aabc"
Output: 1c1b2a
Explanation: aabc
Step1: a2b1c1
Step2: 1c1b2a

Solution:

class Solution 
{ 
    String encryptString(String s) 
    {
       StringBuilder sb = new StringBuilder();
    int count = 1;
    char f = s.charAt(0);
    for (int i = 1; i < s.length(); i++) {
        if (s.charAt(i) == f) {
            count++;
        } else {
            sb.append(f).append(count);
            f = s.charAt(i);
            count = 1;
        }
    }
              sb.append(f).append(count);
              sb.reverse();
    return sb.toString();
    
    }
} 

Time Complexity: O(Length of S)
Space Complexity: O(1)

  1. The method encryptString takes a string s as input and creates a StringBuilder object sb.
  2. Two variables are declared to keep track of the current character and its count. The variable f stores the first character of the input string and the variable count is initialized to 1.
  3. A for loop is used to iterate over the remaining characters of the input string starting from the second character.
  4. If the current character is equal to the previous character f, the count value is incremented.
  5. If the current character is not equal to the previous character f, the character f and its count value are appended to the StringBuilder object sb. Then, the value of f is updated to the current character and the count value is reset to 1.
  6. After the for loop, the character f and its count value are appended to the StringBuilder object sb.
  7. The StringBuilder object sb is reversed and converted to a String using the toString() method.
  8. The encrypted String is returned as the output of the method.

Given two strings a and b. Check whether they contain any common subsequence (non empty) or not.

Example:

Input:
a = "ABEF" b = "CADE"
Output: 1
Explanation: Subsequence "AE" occurs
in both the strings.

Solution:

class Sol
{
    Boolean commonSubseq (String a, String b)
    {for (int i = 0; i < a.length(); i++) {
        for (int j = 0; j < b.length(); j++) {
            
            if (a.charAt(i) == b.charAt(j)) {
                return true;
            }
        }
    }
    
    
    return false;// your code here       
    }
}

Time Complexity: O(n * m), where n is the length of string a and m is the length of string b.
Space Complexity: O(1)

Note: also read about Bucket Sort

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago

Binary Search Tree (BST)

A Binary Search Tree (BST) is a type of binary tree that satisfies the following…

1 year ago