Count Words Obtained After Adding a Letter

You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only.

For each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords.

The conversion operation is described in the following two steps:

  1. Append any lowercase letter that is not present in the string to its end.
    • For example, if the string is "abc", the letters 'd''e', or 'y' can be added to it, but not 'a'. If 'd' is added, the resulting string will be "abcd".
  2. Rearrange the letters of the new string in any arbitrary order.
    • For example, "abcd" can be rearranged to "acbd""bacd""cbda", and so on. Note that it can also be rearranged to "abcd" itself.

Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords.

Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process.

Example 1:

Input: startWords = ["ant","act","tack"], targetWords = ["tack","act","acti"]
Output: 2
Explanation:
- In order to form targetWords[0] = "tack", we use startWords[1] = "act", append 'k' to it, and rearrange "actk" to "tack".
- There is no string in startWords that can be used to obtain targetWords[1] = "act".
  Note that "act" does exist in startWords, but we must append one letter to the string before rearranging it.
- In order to form targetWords[2] = "acti", we use startWords[1] = "act", append 'i' to it, and rearrange "acti" to "acti" itself.

Example 2:

Input: startWords = ["ab","a"], targetWords = ["abc","abcd"]
Output: 1
Explanation:
- In order to form targetWords[0] = "abc", we use startWords[0] = "ab", add 'c' to it, and rearrange it to "abc".
- There is no string in startWords that can be used to obtain targetWords[1] = "abcd".

Constraints:

  • 1 <= startWords.length, targetWords.length <= 5 * 104
  • 1 <= startWords[i].length, targetWords[j].length <= 26
  • Each string of startWords and targetWords consists of lowercase English letters only.
  • No letter occurs more than once in any string of startWords or targetWords.

思路:因为无序,所以分别各自sort array,这样targetword就是找比自己小一个char的string是不是在start set里面;O(word ^2)去判断每个targetword。O(1)去判断,这样快很多。

class Solution {
    public int wordCount(String[] startWords, String[] targetWords) {
        HashSet<String> startSet = new HashSet<>();
        for(String startWord: startWords) {
            char[] ss = startWord.toCharArray();
            Arrays.sort(ss);
            startSet.add(new String(ss));
        }
        
        for(int i = 0; i < targetWords.length; i++) {
            char[] tt = targetWords[i].toCharArray();
            Arrays.sort(tt);
            targetWords[i] = new String(tt);
        }
        int count = 0;
        for(String targetWord: targetWords) {
            for(int i = 0; i < targetWord.length(); i++) {
                StringBuilder sb = new StringBuilder();
                for(int j = 0; j < targetWord.length(); j++) {
                    if(i != j) {
                        sb.append(targetWord.charAt(j));
                    }
                }
                if(startSet.contains(sb.toString())) {
                    count++;
                    break;
                }
            }
        }
        return count;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
To modify the code so that the positive and negative weights are learned through backpropagation, you can define the weights as trainable parameters in the neural network class. Here's an updated version of the code: ```python import torch import torch.nn as nn import torch.optim as optim class RegressionNet(nn.Module): def __init__(self, input_size, hidden_size): super(RegressionNet, self).__init__() # Positive sub-network self.positive_net = nn.Sequential( nn.Linear(input_size, hidden_size), nn.ReLU(), nn.Linear(hidden_size, 1) ) # Negative sub-network self.negative_net = nn.Sequential( nn.Linear(input_size, hidden_size), nn.ReLU(), nn.Linear(hidden_size, 1) ) # Initialize weights randomly self.positive_weight = nn.Parameter(torch.randn(1)) self.negative_weight = nn.Parameter(torch.randn(1)) def forward(self, x): positive_output = self.positive_weight * self.positive_net(x) negative_output = -self.negative_weight * self.negative_net(x) output = positive_output + negative_output return output # Example usage input_size = 10 hidden_size = 20 model = RegressionNet(input_size, hidden_size) # Generate dummy input data batch_size = 32 input_data = torch.randn(batch_size, input_size) target = torch.randn(batch_size, 1) # Define loss function and optimizer criterion = nn.MSELoss() optimizer = optim.SGD(model.parameters(), lr=0.01) # Training loop num_epochs = 100 for epoch in range(num_epochs): # Forward pass output = model(input_data) # Compute loss loss = criterion(output, target) # Backward pass and optimization optimizer.zero_grad() loss.backward() optimizer.step() # Print loss for monitoring print(f"Epoch {epoch+1}/{num_epochs}, Loss: {loss.item()}") # After training, you can access the learned weights positive_weight = model.positive_weight.item() negative_weight = model.negative_weight.item() print(f"Positive weight: {positive_weight}, Negative weight: {negative_weight}") ``` In this updated code, we define `positive_weight` and `negative_weight` as trainable parameters using `nn.Parameter`. These parameters are initialized randomly and will be learned during the training process. Inside the forward pass, we multiply the positive sub-network output by `positive_weight` and the negative sub-network output by `-negative_weight`. The rest of the code remains the same, with the addition of a training loop that performs forward and backward passes, updates the weights using an optimizer (here, stochastic gradient descent), and computes the loss for monitoring purposes. After training, you can access the learned weights using `model.positive_weight.item()` and `model.negative_weight.item()`. I hope this helps! Let me know if you have any further questions.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值