📌  相关文章
📜  查询以查找给定位置之前的字符数

📅  最后修改于: 2021-10-27 17:00:20             🧑  作者: Mango

给定一个仅包含小写字母的长度为N的字符串S。此外,给定Q 个查询,其中每个查询由一个整数P组成,使得1≤ P ≤ N 。任务是找出给定位置P之前相同字母出现的次数。
例子 :

Input: S = "abacsddaa", Q[] = {9, 3}
Output:
3
1
For first query, P = 9, character at 9th location is 'a'.
The number of occurrences of 'a' before P i.e. 9 is three.

Similarly, for P = 3, 3rd character is 'a'.
The number of occurrences of 'a' before P. i.e. 3 is one.

天真的方法对于给出位置“p”的每个查询 Q i ,运行从 1 到“p-1”的循环,并检查该索引处的元素是否等于索引“p”处的元素,如果为真,则增加计数器变量的值加 1。循环完成后,在新行中打印计数器变量的值。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include
using namespace std;
 
int Count(string s, int pos )
{
    // returns character at index pos - 1
    int c = s[pos - 1] ;
    int counter = 0 ;
    for (int i = 0; i < pos-1; i++ )
    {
        if(s[i] == c)
            counter = counter + 1;
    }
    return counter;
}
 
// Driver Code
int main()
{
    string s = "abacsddaa";
    int pos;
    int n = s.length();
    int query[] = {9, 3, 2};
    int Q = sizeof(query) / sizeof(query[0]);
    for(int i = 0; i < Q; i++ )
    {
        pos = query[i] ;
        cout << Count( s, pos ) << endl;
    }
    return 0;
}
 
// This code is contributed by
// divyamohan123


Java
// Java implementation of the approach
class GFG
{
    static int Count(String s, int pos )
    {
        // returns character at index pos - 1
        int c = s.charAt(pos - 1);
        int counter = 0;
        for (int i = 0; i < pos - 1; i++ )
        {
            if(s.charAt(i) == c)
                counter = counter + 1;
        }
        return counter;
    }
     
    // Driver Code
    public static void main (String[] args)
    {
        String s = "abacsddaa";
        int pos;
        int n = s.length();
         
        int query[] = {9, 3, 2};
        int Q = query.length;
         
        for(int i = 0; i < Q; i++)
        {
            pos = query[i];
            System.out.println(Count(s, pos));
        }
    }
}
 
// This code is contributed by AnkitRai01


Python3
# Python 3 implementation of the approach
def Count( s, pos ):
    # returns character at index pos - 1
    c = s[pos - 1]
    counter = 0
    for i in range( pos - 1 ):
        if s[i] == c:
              counter = counter + 1 
    return counter
 
# Driver Code   
if __name__ == "__main__" :
    s = "abacsddaa"
    n = len(s)
    query = [9, 3, 2]
    Q = len(query)
    for i in range( Q ):
        pos = query[i]
        print(Count( s, pos ))


C#
// C# implementation of the approach
using System;
                     
class GFG
{
    static int Count(String s, int pos )
    {
        // returns character at index pos - 1
        int c = s[pos - 1];
        int counter = 0;
        for (int i = 0; i < pos - 1; i++ )
        {
            if(s[i] == c)
                counter = counter + 1;
        }
        return counter;
    }
     
    // Driver Code
    public static void Main (String[] args)
    {
        String s = "abacsddaa";
        int pos;
        int n = s.Length;
         
        int []query = {9, 3, 2};
        int Q = query.Length;
         
        for(int i = 0; i < Q; i++)
        {
            pos = query[i];
            Console.WriteLine(Count(s, pos));
        }
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


C++
// C++ implementation of the approach
#include
using namespace std;
 
void Count(vector temp)
{
    int query[] = {9, 3, 2};
    int Q = sizeof(query) /
            sizeof(query[0]);
    for (int i = 0; i < Q; i++)
    {
        int pos = query[i];
        cout << (temp[pos - 1]) << endl;
    }
}
 
vector processing(string s, int len)
{
    vector temp(len);
    map d;
 
    for (int i = 0; i < len; i++)
    {
        if (d.find(s[i]) == d.end())
        {
            d[s[i]] = i;
        }
        else
        {
            temp[i] = temp[d[s[i]]] + 1;
            d[s[i]] = i;
        }
    }
    return temp;
}
 
// Driver Code
int main()
{
    string s = "abacsddaa";
    int n = s.length();
    vector temp = processing(s, n);
    Count(temp);
}
 
// This code is contributed
// by Surendra_Gangwar


Java
// Java implementation of the approach
import java.util.*;
 
class GFG
{
    static void Count(int[] temp)
    {
        int[] query = {9, 3, 2};
        int Q = query.length;
        for (int i = 0; i < Q; i++)
        {
            int pos = query[i];
            System.out.println(temp[pos - 1]);
        }
    }
 
    static int[] processing(String s, int len)
    {
        int[] temp = new int[len];
        HashMap d = new HashMap();
        for (int i = 0; i < len; i++)
        {
            if (!d.containsKey(s.charAt(i)))
            {
                d.put(s.charAt(i), i);
            }
            else
            {
                temp[i] = temp[d.get(s.charAt(i))] + 1;
                d.put(s.charAt(i), i);
            }
        }
        return temp;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String s = "abacsddaa";
        int n = s.length();
        int[] temp = processing(s, n);
        Count(temp);
    }
}
 
// This code is contributed by Rajput-Ji


Python3
# Python 3 implementation of the approach
def Count( temp ):
    query = [9, 3, 2]
    Q = len(query)
    for i in range( Q ):
        pos = query[i]
        print( temp[pos-1] )
def processing( s ):
    temp = [ 0 ] * len( s )
    d = dict( )
    for i in range( len( s ) ):
        if s[i] not in d:
            d[ s[i] ] = i
        else:
            temp[i] = temp[ d[ s[i] ] ] + 1
            d[ s[i] ] = i
    return temp
     
# Driver Code   
if __name__ == "__main__" :
    s = "abacsddaa"
    n = len(s)
    temp = processing( s )
    Count( temp )


C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
    static void Count(int[] temp)
    {
        int[] query = {9, 3, 2};
        int Q = query.Length;
        for (int i = 0; i < Q; i++)
        {
            int pos = query[i];
            Console.WriteLine(temp[pos - 1]);
        }
    }
 
    static int[] processing(String s, int len)
    {
        int[] temp = new int[len];
        Dictionary d = new Dictionary();
        for (int i = 0; i < len; i++)
        {
            if (!d.ContainsKey(s[i]))
            {
                d.Add(s[i], i);
            }
            else
            {
                temp[i] = temp[d[s[i]]] + 1;
                d[s[i]] = i;
            }
        }
        return temp;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        String s = "abacsddaa";
        int n = s.Length;
        int[] temp = processing(s, n);
        Count(temp);
    }
}
 
// This code is contributed by PrinciRaj1992


输出:
3
1
0

时间复杂度: O(N)
空间复杂度: O(1)
更好的方法:使用哈希或字典和辅助空间。
创建和辅助数组说‘temp’ ,它初始化为零和哈希表或字典‘d’
最初是空的。出于预处理目的,即在 temp 中的索引 pos 处存储索引 ‘pos’ 处元素的先前计数。

Preprocessing function
Pseudo Code:
function Preprocess(s):
      for i=1 to length(s),
           if s(i) not in hash_table,
                hash_table(s(i)) := i,
                end;
           else,
                auxiliary_array(i) = hash_table(s(i)) + 1,
                hash_table(s(i)) =  i,
                end;                

它将所有需要的值放在辅助数组的相应索引处。对于每个查询 Q,在 temp 中的位置 ‘pos’ 打印 val。

C++

// C++ implementation of the approach
#include
using namespace std;
 
void Count(vector temp)
{
    int query[] = {9, 3, 2};
    int Q = sizeof(query) /
            sizeof(query[0]);
    for (int i = 0; i < Q; i++)
    {
        int pos = query[i];
        cout << (temp[pos - 1]) << endl;
    }
}
 
vector processing(string s, int len)
{
    vector temp(len);
    map d;
 
    for (int i = 0; i < len; i++)
    {
        if (d.find(s[i]) == d.end())
        {
            d[s[i]] = i;
        }
        else
        {
            temp[i] = temp[d[s[i]]] + 1;
            d[s[i]] = i;
        }
    }
    return temp;
}
 
// Driver Code
int main()
{
    string s = "abacsddaa";
    int n = s.length();
    vector temp = processing(s, n);
    Count(temp);
}
 
// This code is contributed
// by Surendra_Gangwar

Java

// Java implementation of the approach
import java.util.*;
 
class GFG
{
    static void Count(int[] temp)
    {
        int[] query = {9, 3, 2};
        int Q = query.length;
        for (int i = 0; i < Q; i++)
        {
            int pos = query[i];
            System.out.println(temp[pos - 1]);
        }
    }
 
    static int[] processing(String s, int len)
    {
        int[] temp = new int[len];
        HashMap d = new HashMap();
        for (int i = 0; i < len; i++)
        {
            if (!d.containsKey(s.charAt(i)))
            {
                d.put(s.charAt(i), i);
            }
            else
            {
                temp[i] = temp[d.get(s.charAt(i))] + 1;
                d.put(s.charAt(i), i);
            }
        }
        return temp;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String s = "abacsddaa";
        int n = s.length();
        int[] temp = processing(s, n);
        Count(temp);
    }
}
 
// This code is contributed by Rajput-Ji

蟒蛇3

# Python 3 implementation of the approach
def Count( temp ):
    query = [9, 3, 2]
    Q = len(query)
    for i in range( Q ):
        pos = query[i]
        print( temp[pos-1] )
def processing( s ):
    temp = [ 0 ] * len( s )
    d = dict( )
    for i in range( len( s ) ):
        if s[i] not in d:
            d[ s[i] ] = i
        else:
            temp[i] = temp[ d[ s[i] ] ] + 1
            d[ s[i] ] = i
    return temp
     
# Driver Code   
if __name__ == "__main__" :
    s = "abacsddaa"
    n = len(s)
    temp = processing( s )
    Count( temp )

C#

// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
    static void Count(int[] temp)
    {
        int[] query = {9, 3, 2};
        int Q = query.Length;
        for (int i = 0; i < Q; i++)
        {
            int pos = query[i];
            Console.WriteLine(temp[pos - 1]);
        }
    }
 
    static int[] processing(String s, int len)
    {
        int[] temp = new int[len];
        Dictionary d = new Dictionary();
        for (int i = 0; i < len; i++)
        {
            if (!d.ContainsKey(s[i]))
            {
                d.Add(s[i], i);
            }
            else
            {
                temp[i] = temp[d[s[i]]] + 1;
                d[s[i]] = i;
            }
        }
        return temp;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        String s = "abacsddaa";
        int n = s.Length;
        int[] temp = processing(s, n);
        Count(temp);
    }
}
 
// This code is contributed by PrinciRaj1992
输出:
3
1
0

时间复杂度: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程