Implement-Strstr——python

本文介绍了一个简单的strStr()函数实现方法,该函数用于在haystack字符串中查找needle字符串首次出现的位置。通过逐字符比较的方式完成匹配过程,并考虑了边界情况如needle为空字符串的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

“””
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = “hello”, needle = “ll”
输出: 2
示例 2:
输入: haystack = “aaaaa”, needle = “bba”
输出: -1
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
“”“

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if len(haystack) == len(needle):
            if haystack == needle:
                return 0
            else:
                return -1

        for i in xrange(0, len(haystack)):
            k = i
            j = 0
            while j < len(needle) and k < len(haystack) and haystack[k] == needle[j]:
                j += 1
                k += 1
            if j == len(needle):
                return i
        return -1 if needle else 0
### RANSAC-Based ICP Implementation in Python The Iterative Closest Point (ICP) algorithm is widely used for aligning point clouds. Incorporating the Random Sample Consensus (RANSAC) method enhances robustness against outliers during alignment processes. While Ziv Yaniv has implemented RANSAC using C++[^1], specific implementations combining both RANSAC and ICP within a single framework are less common but do exist. Below demonstrates how one might implement an RANSAC-based ICP approach in Python: #### Example Code of RANSAC-Based ICP Algorithm ```python import numpy as np from sklearn.neighbors import NearestNeighbors def best_fit_transform(A, B): """ Calculates the least-squares best-fit transform that maps corresponding points A to B. Args: A: Nx3 numpy array representing source points. B: Nx3 numpy array representing destination points. Returns: T: 4x4 homogeneous transformation matrix mapping from A to B. R: 3x3 rotation matrix component of T. t: 3x1 translation vector component of T. """ assert len(A) == len(B) # Get centroids of each set of points centroid_A = np.mean(A, axis=0) centroid_B = np.mean(B, axis=0) # Centered coordinates relative to respective centroids AA = A - centroid_A BB = B - centroid_B # Compute covariance matrix H between centered coordinate sets H = np.dot(AA.T, BB) # Perform singular value decomposition on H U, S, Vt = np.linalg.svd(H) # Calculate optimal rotation matrix R R = np.dot(Vt.T, U.T) # Special reflection case handling if np.linalg.det(R) < 0: Vt[-1,:] *= -1 R = np.dot(Vt.T, U.T) # Optimal translation vector calculation based on centroids difference after applying computed rotation t = centroid_B.T - np.dot(R,centroid_A.T) # Construct final rigid body motion transformation matrix incorporating calculated rotation & translation components T = np.identity(4) T[:3,:3] = R T[:3,3] = t return T, R, t def icp(A, B, init_pose=None, max_iterations=20, tolerance=0.001): ''' Performs iterative closest point matching with optional initial pose estimation Args: A: MxN numpy array containing source data points where N represents dimensionality typically being equal to three indicating spatial Cartesian XYZ positions. B: KxN numpy array holding target/reference dataset also having same dimensional structure like 'A'. init_pose: Initial guess at transformation relating two datasets expressed via affine/homogeneous representation; defaults None implying identity operation applied initially before iterations commence. max_iterations: Maximum number of times allowed loop execution until convergence criteria met or exceeded limit reached. tolerance: Threshold below which residual error change considered negligible signifying satisfactory fit quality achieved thus terminating procedure early. Yields: Transformation matrices iteratively refined throughout process along with associated registration errors per cycle completed. ''' src = np.ones((4,A.shape[0])) ref = np.ones((4,B.shape[0])) src[:3,:] = np.copy(A.T) ref[:3,:] = np.copy(B.T) prev_error = 0 if not isinstance(init_pose,np.ndarray): T = np.eye(4) else: T = init_pose nbrs = NearestNeighbors(n_neighbors=1, algorithm='ball_tree').fit(ref.T[:,:3]) for i in range(max_iterations): distances, indices = nbrs.kneighbors(np.dot(T,src).T[:,:3]) correspondences = zip(indices.flatten(),range(len(distances))) filtered_correspondence_pairs = [] for idx_src,idx_ref in list(correspondences): distance_to_nearest_neighbor = distances[idx_ref][0] if distance_to_nearest_neighbor<tolerance*10: filtered_correspondence_pairs.append([idx_ref,idx_src]) P = np.array(filtered_correspondence_pairs) if len(P)==0: break matched_source_points = src[:,P[:,0]] matched_reference_points = ref[:,P[:,1]] new_T,_,_ = best_fit_transform(matched_source_points[:-1].T, matched_reference_points[:-1].T) T = np.dot(new_T,T) mean_dist = sum([np.linalg.norm(src[:,i]-ref[:,j]) \ for j,i in filtered_correspondence_pairs])/len(filtered_correspondence_pairs) if abs(prev_error-mean_dist)<tolerance: break prev_error = mean_dist yield {'transformation':new_T,'error':mean_dist} def ransac_icp(source_pts, target_pts, num_iter=1000, threshold=0.05): """Implementation of RANSAC wrapper around basic ICP routine.""" best_inliers_ratio = 0 best_transf_matrix = None n_samples = min(3,source_pts.shape[0]) # Minimum sample size required by ICP function internally for _ in range(num_iter): sampled_indices = np.random.choice( range(source_pts.shape[0]), replace=False, size=n_samples) current_sampled_source = source_pts[sampled_indices] current_sampled_target = target_pts[sampled_indices] try: transf_gen = icp(current_sampled_source,current_sampled_target,max_iterations=1) for result in transf_gen: transformed_full_set = np.dot(result['transformation'],np.vstack((source_pts.T,np.ones((1,source_pts.shape[0]))))) residuals = ((transformed_full_set[:3].T-target_pts)**2).sum(axis=-1)**0.5 mask = residuals<threshold ratio_of_inliers = float(mask.sum())/float(residuals.size) if ratio_of_inliers>best_inliers_ratio: best_inliers_ratio=ratio_of_inliers
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值