Showing posts with label String. Show all posts
Showing posts with label String. Show all posts

Removing Stars From a String

Given a string s, which contains stars *.

In one operation, you can.

Choose a star in s.

Remove the closest non-star character to its left, as well as remove the star itself.

Return the string after all stars have been removed.

Note:

The input will be generated such that the operation is always possible.

It can be shown that the resulting string will always be unique.

For Example

Input: helll*o

Output: hello

Approach

Explanation:

We need to iterate the input string from start to end and do the below steps.

Step 1: If we encounter * at the ith position then we remove the last appended/added character from the resulting string.

Step 2: If we encounter another character then * then we append the current character into our resulting string.

Let's take one example

Input:: helll*o

res=""

i=0,ch=h, res="h"

i=1, ch=e, res="he",

i=2,ch=l,res="hel"

i=3,ch=l,res="hell"

i=4,ch=l,res="helll"

i=5,ch=*,res="hell"

i=6, ch=o, res="hello"

Java

public class RemoveStars {
    public static void main(String[] args) {
        {
            String input = "helll*o";
            System.out.println(removeStars(input));
        }

    }

    public static String removeStars(String s) {

        // create string builder to store the resulting
        // string
        StringBuilder str = new StringBuilder();

        // iterate through the whole string
        for (int i = 0; i < s.length(); i++) {
            // Case 1:: If current character is '*' then
            // remove from the resulting string if resulting string
            // size is greater then 0
            if (s.charAt(i) == '*') {
                if (str.length() > 0) {
                    str.deleteCharAt(str.length() - 1);
                }

            }
            // Case:: If current character is other then '*' then
            // append into the resulting string
            else {
                str.append(s.charAt(i));
            }
        }

        // return the final string
        return str.toString();

    }
}

C++

#include <bits/stdc++.h>
using namespace std;

string removeStars(string s)
{
    string res = "";
    for (int i = 0; i < s.size(); i++)
    {
        if (s[i] == '*')
        {
            if (res.size() > 0)
            {
                res.pop_back();
            }
        }
        else
        {
            res += s[i];
        }
    }
    return res;
}
int main()
{
    string str = "helll*o";
    cout << removeStars(str);
    return 0;
}


String toUpperCase() locale in Java

toUpperCase(): This method is available in java.lang.String class of Java.

Syntax:

String java.lang.String.toUpperCase(Locale locale)

This method converts all of the characters in this String to uppercase using the rules of the given Locale. Case mapping is based on the Unicode Standard version specified by the Character class.

Parameters: One parameter is required for this method.

locale: use the case transformation rules for this locale.

Returns: the String, converted to uppercase.

For Example:

String str = "Hello"

toUpperCase(Locale.ENGLISH) = > It returns HELLO.

Approach

Java

import java.util.Locale;

public class ToUpperCaseLocale {
    public static void main(String[] args) {
        String str = "Hello";

        System.out.println(str.toUpperCase(Locale.ENGLISH));
    }
}

Output:

HELLO


Some more methods of String

charAt() It returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

codePointAt()It returns the character (Unicode code point) at the specified index. The index refers to char values(Unicode code units) and ranges from 0 to length() - 1.

codePointBefore()It returns the character (Unicode code point) before the specified index.

codePointCount()It returns the number of Unicode code points in the specified text range of this String.

compareTo()It compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings.

compareToIgnoreCase()It compares two strings lexicographically, ignoring case differences.

concat()It concatenates the specified string to the end of this string.

contains()It returns true if and only if this string contains the specified sequence of char values.

contentEquals(CharSequence cs): It compares this string to the specified CharSequence.

contentEquals(StringBuffer sb) It compares this string to the specified StringBuffer.

String.copyValueOf(char[] data)It returns the String representation of the char array characters.

String.copyValueOf(char[] data, int offset, int count) It returns the string that contains the character of the specified sub-array.

endsWith()It tests if this string ends with the specified suffix.

equals()It compares this string to the specified object.

equalsIgnoreCase()It Compares this String to another String, ignoring case considerations.

String.format()It returns a formatted string using the specified format string and arguments.

formatted()It formats using this string as the format string, and the supplied arguments.

String.format(Locale l, String format, Object... args): It returns a formatted string using the specified locale, format string, and arguments.

getBytes()It encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

getBytes(Charset charset): It encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array. 

getBytes(String charsetName)It encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.

hashCode()It returns a hash code for this string.

indent()It adjusts the indentation of each line of this string based on the value of n and normalizes line termination characters.

indexOf(int ch)It returns the index within this string of the first occurrence of the specified character. 

indexOf(int ch, int fromIndex)It returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

indexOf(String str)It returns the index within this string of the first occurrence of the specified substring.

indexOf(String str, int fromIndex)It returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

intern()It returns a canonical representation for the string object.

isBlank()It returns true if the string is empty or contains only white space code points, otherwise false.

isEmpty()It returns true if, and only if, length() is 0.

String.join(): It returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.

String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)It returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.

lastIndexOf(int ch) It returns the index within this string of the last occurrence of the specified character.

lastIndexOf(int ch, int fromIndex)It returns the index within this string of the last occurrence of the specified character.

lastIndexOf(String str)It returns the index within this string of the last occurrence of the specified substring.

lastIndexOf(String str, int fromIndex): It returns the index within this string of the last occurrence of the specified substring.

length()It returns the length of this string.

matches()It tells whether or not this string matches the given regular expression.

offsetByCodePoints():It returns the index within this String that is offset from the given index by codePointOffset code points.

regionMatches(int toffset, String other, int ooffset, int len)It tests if two string regions are equal.

regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)It tests if two string regions are equal. A substring of this String object is compared to a substring of the argument other.

repeat()It returns a string whose value is the concatenation of this string repeated count times.

replaceAll()It replaces each substring of this string that matches the given regular expression with the given replacement.

replace(char oldChar, char newChar) It returns a string resulting from replacing all occurrences of oldChar in this string with newChar.

replace(CharSequence target, CharSequence replacement)It replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.

replaceFirst()It replaces the first substring of this string that matches the given regular expression with the given replacement.

split(String regex)It splits this string around matches of the given regular expression.

split(String regex, int limit)It splits this string around matches of the given regular expression.

startsWith(String prefix)It tests if this string starts with the specified prefix.

startsWith(String prefix, int offset)It tests if the substring of this string beginning at the specified index starts with the specified prefix.

strip()It returns a string whose value is this string, with all leading and trailing white space removed.

stripIndent()It returns a string whose value is this string, with incidental white space removed from the beginning and end of every line.

stripLeading()It returns a string whose value is this string, with all leading white space removed.

stripTrailing()It returns a string whose value is this string, with all trailing white space removed.

subSequence() It returns a character sequence that is a subsequence of this sequence.

substring(int beginIndex)It returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

substring(int beginIndex, int endIndex)It returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex -1.

toCharArray()It converts this string to a new character array.

toLowerCase()It converts all of the characters in this String to lowercase using the rules of the default locale.

toLowerCase(Locale locale)It converts all of the characters in this String to lowercase using the rules of the given Locale.

toString()This object (which is already a string!) is itself returned.

toUpperCase()This method converts all of the characters in this String to uppercase using the rules of the default locale.

toUpperCase(Locale locale)This method converts all of the characters in this String to uppercase using the rules of the given Locale. Case mapping is based on the Unicode Standard version specified by the Character class.

translateEscapes()This method returns a string whose value is this string, with escape sequences translated as if in a string literal.

trim()This method returns a string whose value is this string, with all leading and trailing space removed.

String.valueOf(boolean b)This method returns the string representation of the boolean argument.

String.valueOf(char c) This method returns the string representation of the char argument.

String.valueOf(char[] data) This method returns the string representation of the char array argument. The contents of the character array are copied; subsequent modification of the character array does not affect the returned string.

String.valueOf(char[] data, int offset, int count)his method returns the string representation of a specific subarray of the char array argument.

String.valueOf(double d)This method returns the string representation of the double argument.

String.valueOf(float f)This method returns the string representation of the float argument.

String.valueOf(int i)This method returns the string representation of the int argument.

String.valueOf(long l)This method returns the string representation of the long argument.

Number of Strings That Appear as Substrings in Word

Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in the word.

substring is a contiguous sequence of characters within a string.

Example 1:

Input: patterns = ["a","abc","bc","d"], word = "abc"
Output: 3
Explanation:
- "a" appears as a substring in "abc".
- "abc" appears as a substring in "abc".
- "bc" appears as a substring in "abc".
- "d" does not appear as a substring in "abc".
3 of the strings in patterns appear as a substring in word.

Example 2:

Input: patterns = ["a","b","c"], word = "aaaaabbbbb"
Output: 2
Explanation:
- "a" appears as a substring in "aaaaabbbbb".
- "b" appears as a substring in "aaaaabbbbb".
- "c" does not appear as a substring in "aaaaabbbbb".
2 of the strings in patterns appear as a substring in word.

Approach

Java

public class NumberOfStrings {
    public static void main(String[] args) {

        String[] patterns = { "a""abc""bc""d" };
        String word = "abc";

        System.out.println(numOfStrings(patterns, word));

    }

    static int numOfStrings(String[] patternsString word) {
        int totalCount = 0;

        for (int i = 0; i < patterns.length; i++) {
            if (word.contains(patterns[i]))
                totalCount++;
        }
        return totalCount;
    }

}

Output:

3

C++

#include <bits/stdc++.h>
using namespace std;

int numOfStrings(vector<string&patternsstring word)
{
    int totalCount = 0;

    for (int i = 0i < patterns.size(); i++)
    {
        if (word.find(patterns[i]) != string::npos)
            totalCount++;
    }
    return totalCount;
}

int main()
{
    vector<stringpatterns = {"a""abc""bc""d"};
    string word = "abc";

    cout << numOfStrings(patternsword<< "\n";

    return 0;
}

Output:

3


Minimum Time to Type Word Using Special Typewriter

There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'.

Each second, you may perform one of the following operations

1. Move the pointer one character counterclockwise or clockwise.

2. Type the character the pointer is currently on.

Given a string word, return the minimum number of seconds to type out the characters in a word.

Example 1:

Input: word = "abc"
Output: 5
Explanation: 
The characters are printed as follows:
- Type the character 'a' in 1 second since the pointer is initially on 'a'.
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer clockwise to 'c' in 1 second.
- Type the character 'c' in 1 second.

Example 2:

Input: word = "bza"
Output: 7
Explanation:
The characters are printed as follows:
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer counterclockwise to 'z' in 2 seconds.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'a' in 1 second.
- Type the character 'a' in 1 second.

Approach

Java

public class MinTimeToTypeWord {
    public static void main(String[] args) {

        String word = "bza";

        System.out.println(minTimeToType(word));

    }

    static int minTimeToType(String word) {

        int totalTime = 0;

        // initially start character is 'a'
        int start = 'a';

        // iterate through whole string
        for (int i = 0; i < word.length(); i++) {
            // check for which direction we need to go
            int clockDir = Math.abs((word.charAt(i) - 'a') - 
(start - 'a'));

            // update the clockdir as min of clockwise and
            // anti clockwise
            clockDir = Math.min(clockDir, 26 - clockDir);

            // add clockDir value to final result +1 for type 
//that character
            totalTime += clockDir + 1;

            // update the start character as current character
            start = word.charAt(i);
        }

        return totalTime;
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

int minTimeToType(string word)
{

    int totalTime = 0;

    //initially start character is 'a'
    int start = 'a';

    //itearate through whole string
    for (int i = 0i < word.size(); i++)
    {
        //check for which direction we need to go
        int clockDir = abs((word[i] - 'a') - (start - 'a'));

        //update the clockdir as min of clockwise and
        //anticlockwise
        clockDir = min(clockDir26 - clockDir);

        //add clockDir value to final result +1 for 
//type that character
        totalTime += clockDir + 1;

        //update the start character as current character
        start = word[i];
    }

    return totalTime;
}

int main()
{
    string word = "bza";

    cout << minTimeToType(word<< "\n";

    return 0;
}