📌  相关文章
📜  给定字符串中相同字符出现之间所有距离的总和

📅  最后修改于: 2021-09-04 08:06:06             🧑  作者: Mango

给定一个字符串S ,任务是从包含相同字符的给定字符串中找到所有索引对之间的距离总和。

例子:

朴素方法:解决问题的最简单方法是遍历字符串,对于遇到的每个字符,遍历其右侧的剩余字符串以查找该字符的出现次数。对于找到的每个重复字符,继续将相关索引之间的绝对差异添加到答案中。最后,打印得到的总和。

时间复杂度: O(N 2 )
辅助空间: O(1)

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to calculate the sum
// of distances between occurrences
// of same characters in a string
int findSum(string s)
{
    int sum = 0;
    for (int i = 0; i < s.size(); i++) {
        for (int j = i + 1; j < s.size(); j++) {
 
            // If similar characters are found
            if (s[i] == s[j]) {
 
                // Add the difference
                // of their positions
                sum += (j - i);
            }
        }
    }
 
    // Return the answer
    return sum;
}
 
// Driver Code
int main()
{
    string s = "ttt";
    cout << findSum(s) << endl;
}


Java
// Java program for the above approach
import java.util.*;
class GFG{
 
// Function to calculate the sum
// of distances between occurrences
// of same characters in a String
static int findSum(String s)
{
    int sum = 0;
    for (int i = 0; i < s.length(); i++)
    {
        for (int j = i + 1; j < s.length(); j++)
        {
            // If similar characters are found
            if (s.charAt(i) == s.charAt(j))
            {
                // Add the difference
                // of their positions
                sum += (j - i);
            }
        }
    }
 
    // Return the answer
    return sum;
}
 
// Driver Code
public static void main(String[] args)
{
    String s = "ttt";
    System.out.print(findSum(s) + "\n");
}
}
// This code is contributed by shikhasingrajput


Python3
# Python3 program for the above approach
  
# Function to calculate the sum
# of distances between occurrences
# of same characters in a string
def findSum(s):
     
    sum = 0
    for i in range(len(s)):
        for j in range(i + 1, len(s)):
  
            # If similar characters are found
            if (s[i] == s[j]):
  
                # Add the difference
                # of their positions
                sum += (j - i)
  
    # Return the answer
    return sum
 
# Driver Code
s = "ttt"
 
print(findSum(s))
 
# This code is contributed by code_hunt


C#
// C# program for
// the above approach
using System;
class GFG{
 
// Function to calculate the sum
// of distances between occurrences
// of same characters in a String
static int findSum(String s)
{
  int sum = 0;
  for (int i = 0; i < s.Length; i++)
  {
    for (int j = i + 1; j < s.Length; j++)
    {
      // If similar characters
      // are found
      if (s[i] == s[j])
      {
        // Add the difference
        // of their positions
        sum += (j - i);
      }
    }
  }
 
  // Return the answer
  return sum;
}
 
// Driver Code
public static void Main(String[] args)
{
  String s = "ttt";
  Console.Write(findSum(s) + "\n");
}
}
  
// This code is contributed by shikhasingrajput


Javascript


Javascript


Java
// Java program for the above approach
import java.io.*;
 
class GFG{
 
// Function to calculate the sum
// of distances between occurrences
// of same characters in a string
static int findSum(String s)
{
    int[] visited = new int[256];
    int[] distance = new int[256];
 
    // Initially make all the distances
    // and number of characters visited as 0
    for(int i = 0; i < 256; i++)
    {
        visited[i] = 0;
        distance[i] = 0;
    }
 
    int sum = 0;
 
    for(int i = 0; i < s.length(); i++)
    {
         
        // Assuming that all the similar
        // characters are located at index 0
 
        // Add visited[s[i]]*i to sum
        // and subtract the distances of
        // characters from index 0
        sum += visited[s.charAt(i)] * i -
              distance[s.charAt(i)];
 
        // Increment the number of
        // visited characters
        visited[s.charAt(i)]++;
 
        // Add the distance of the
        // character from position 0
        // i.e., (i - 0) = i
        distance[s.charAt(i)] += i;
    }
 
    // Return the answer
    return sum;
}
 
// Driver code
public static void main (String[] args)
{
    String s = "ttt";
     
    // Function call
    System.out.println(findSum(s));
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program for the above approach
 
# Function to calculate the sum
# of distances between occurrences
# of same characters in a string
def findSum(s):
    visited = [0 for i in range(256)];
    distance = [0 for i in range(256)];
 
    # Initially make all
    # the distances and number
    # of characters visited as 0
    for i in range(256):
        visited[i] = 0;
        distance[i] = 0;   
 
    sum = 0;
 
    for i in range(len(s)):
 
        # Assuming that all the similar
        # characters are located at index 0
 
        # Add visited[s[i]]*i to sum
        # and subtract the distances of
        # characters from index 0
        sum += visited[ord(s[i])] * i - distance[ord(s[i])];
 
        # Increment the number of
        # visited characters
        visited[ord(s[i])] += 1;
 
        # Add the distance of the
        # character from position 0
        # i.e., (i - 0) = i
        distance[ord(s[i])] += i;   
 
    # Return the answer
    return sum;
 
# Driver code
if __name__ == '__main__':
   
    s = "ttt";
 
    # Function call
    print(findSum(s));
 
# This code is contributed by Rajput-Ji


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to calculate the sum
// of distances between occurrences
// of same characters in a string
static int findSum(String s)
{
    int[] visited = new int[256];
    int[] distance = new int[256];
 
    // Initially make all the distances
    // and number of characters visited as 0
    for(int i = 0; i < 256; i++)
    {
        visited[i] = 0;
        distance[i] = 0;
    }
     
    int sum = 0;
     
    for(int i = 0; i < s.Length; i++)
    {
         
        // Assuming that all the similar
        // characters are located at index 0
 
        // Add visited[s[i]]*i to sum
        // and subtract the distances of
        // characters from index 0
        sum += visited[s[i]] * i -
              distance[s[i]];
 
        // Increment the number of
        // visited characters
        visited[s[i]]++;
 
        // Add the distance of the
        // character from position 0
        // i.e., (i - 0) = i
        distance[s[i]] += i;
    }
 
    // Return the answer
    return sum;
}
 
// Driver code
public static void Main(String[] args)
{
    String s = "ttt";
     
    // Function call
    Console.WriteLine(findSum(s));
}
}
 
// This code is contributed by Amit Katiyar


C++
#include 
using namespace std;
 
int main() {
 
    cout<<"GFG!";
    return 0;
}


输出:
4

高效的方法:上述方法可以基于以下观察进行优化:

  • 最初对于每个字符,假设它的所有相似字符都在索引0 处
  • 根据上述假设,所需的总和等于:

因此,请按照以下步骤解决问题:

  • 初始化两个数组访问[]距离[]分别存储每个字符存在字符串中和每个字符的先前出现之间的距离的频率。
  • 遍历字符串并对遇到的每个字符,即 S[i],更新以下内容:
    • visited[S[i] * i – distance[S[i]] 添加到所需的总和。
    • 增加visited[S[i]]以增加字符的频率。
    • distance[S[i]]增加i ,以增加与先前出现的S[i]的距离被认为是 0。
  • 完成上述步骤后,打印获得的总和。

下面是上述方法的实现:

Javascript


Java

// Java program for the above approach
import java.io.*;
 
class GFG{
 
// Function to calculate the sum
// of distances between occurrences
// of same characters in a string
static int findSum(String s)
{
    int[] visited = new int[256];
    int[] distance = new int[256];
 
    // Initially make all the distances
    // and number of characters visited as 0
    for(int i = 0; i < 256; i++)
    {
        visited[i] = 0;
        distance[i] = 0;
    }
 
    int sum = 0;
 
    for(int i = 0; i < s.length(); i++)
    {
         
        // Assuming that all the similar
        // characters are located at index 0
 
        // Add visited[s[i]]*i to sum
        // and subtract the distances of
        // characters from index 0
        sum += visited[s.charAt(i)] * i -
              distance[s.charAt(i)];
 
        // Increment the number of
        // visited characters
        visited[s.charAt(i)]++;
 
        // Add the distance of the
        // character from position 0
        // i.e., (i - 0) = i
        distance[s.charAt(i)] += i;
    }
 
    // Return the answer
    return sum;
}
 
// Driver code
public static void main (String[] args)
{
    String s = "ttt";
     
    // Function call
    System.out.println(findSum(s));
}
}
 
// This code is contributed by offbeat

蟒蛇3

# Python3 program for the above approach
 
# Function to calculate the sum
# of distances between occurrences
# of same characters in a string
def findSum(s):
    visited = [0 for i in range(256)];
    distance = [0 for i in range(256)];
 
    # Initially make all
    # the distances and number
    # of characters visited as 0
    for i in range(256):
        visited[i] = 0;
        distance[i] = 0;   
 
    sum = 0;
 
    for i in range(len(s)):
 
        # Assuming that all the similar
        # characters are located at index 0
 
        # Add visited[s[i]]*i to sum
        # and subtract the distances of
        # characters from index 0
        sum += visited[ord(s[i])] * i - distance[ord(s[i])];
 
        # Increment the number of
        # visited characters
        visited[ord(s[i])] += 1;
 
        # Add the distance of the
        # character from position 0
        # i.e., (i - 0) = i
        distance[ord(s[i])] += i;   
 
    # Return the answer
    return sum;
 
# Driver code
if __name__ == '__main__':
   
    s = "ttt";
 
    # Function call
    print(findSum(s));
 
# This code is contributed by Rajput-Ji

C#

// C# program for the above approach
using System;
 
class GFG{
 
// Function to calculate the sum
// of distances between occurrences
// of same characters in a string
static int findSum(String s)
{
    int[] visited = new int[256];
    int[] distance = new int[256];
 
    // Initially make all the distances
    // and number of characters visited as 0
    for(int i = 0; i < 256; i++)
    {
        visited[i] = 0;
        distance[i] = 0;
    }
     
    int sum = 0;
     
    for(int i = 0; i < s.Length; i++)
    {
         
        // Assuming that all the similar
        // characters are located at index 0
 
        // Add visited[s[i]]*i to sum
        // and subtract the distances of
        // characters from index 0
        sum += visited[s[i]] * i -
              distance[s[i]];
 
        // Increment the number of
        // visited characters
        visited[s[i]]++;
 
        // Add the distance of the
        // character from position 0
        // i.e., (i - 0) = i
        distance[s[i]] += i;
    }
 
    // Return the answer
    return sum;
}
 
// Driver code
public static void Main(String[] args)
{
    String s = "ttt";
     
    // Function call
    Console.WriteLine(findSum(s));
}
}
 
// This code is contributed by Amit Katiyar

C++

#include 
using namespace std;
 
int main() {
 
    cout<<"GFG!";
    return 0;
}
输出:
4

时间复杂度: O(N)
辅助空间: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live